Get ip java wifi

Getting WiFi Direct IP address of my device

Why are you passing WIFI_P2P_SERVICE to getSystemService() when you need a WifiManager ? Shouldn’t you be passing Context.WIFI_SERVICE instead?

7 Answers 7

Unfortunately, there’s no way to get your own IP address, and the general principle of operation is slightly different:

  • All the operations will be made with the WiFiP2PManager
  • call initialize to get a Channel, all other operations needs this channel.
  • after you discoverPeers and connect to one of them
  • you can requestGroupInfo that will tell you if that device is the group owner and what is the group owner IP address. So non-owners can connect to the owner using the supplied address and the owner will listen to connections.
  • you can also requestPeers that will give you a list of all connected peers. That includes MAC addresses and names.

The call Context.getSystemService(Context.WIFI_P2P_SERVICE) will give you a WiFiP2PManager.

And yes, you’ll need a bunch of WiFI permission such as ACCESS_WIFI_STATE , CHANGE_WIFI_STATE among others.

it means you have worked in android P2P ,I have few questions, will you please give me your email address or facebook address, If you wanna help?

when a non owner connects to the owner, the owner can get the address of the connection and can use it or send it to the non owner

send out the peer’s local ip address (starting with 192.168.x.x) to the group owner. After this «handshake», which doesn’t really take time, it’s all good to go. Did not find any other way to get the peer’s ip addresses, the only information provided by GroupListener/PeerListener/. is the mac address.

This does not answer the question — OP wants to know how to get own IP address not how to notify a GO of an already known IP address. The point is that we don’t know where to get the 192.168.x.x from!

public static String getIpAddress() < try < Listinterfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); /* * for (NetworkInterface networkInterface : interfaces) < Log.v(TAG, * "interface name " + networkInterface.getName() + "mac = " + * getMACAddress(networkInterface.getName())); >*/ for (NetworkInterface intf : interfaces) < if (!getMACAddress(intf.getName()).equalsIgnoreCase( Globals.thisDeviceAddress)) < // Log.v(TAG, "ignore the interface " + intf.getName()); // continue; >if (!intf.getName().contains("p2p")) continue; Log.v(TAG, intf.getName() + " " + getMACAddress(intf.getName())); List addrs = Collections.list(intf .getInetAddresses()); for (InetAddress addr : addrs) < // Log.v(TAG, "inside"); if (!addr.isLoopbackAddress()) < // Log.v(TAG, "isnt loopback"); String sAddr = addr.getHostAddress().toUpperCase(); Log.v(TAG, "ip=" + sAddr); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (isIPv4) < if (sAddr.contains("192.168.49.")) < Log.v(TAG, "ip = " + sAddr); return sAddr; >> > > > > catch (Exception ex) < Log.v(TAG, "error in parsing"); >// for now eat exceptions Log.v(TAG, "returning empty ip address"); return ""; > public static String getMACAddress(String interfaceName) < try < Listinterfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) < if (interfaceName != null) < if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; >byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) buf.append(String.format("%02X:", mac[idx])); if (buf.length() >0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); > > catch (Exception ex) < >// for now eat exceptions return ""; /* * try < // this is so Linux hack return * loadFileAsString("/sys/class/net/" +interfaceName + * "/address").toUpperCase().trim(); >catch (IOException ex) < return * null; >*/ > 

In API level 23, InetAddressUtils is deprecated. So check (inetAddress instanceof Inet4Address) instead InetAddressUtils.isIPv4Address(sAddr)

Читайте также:  Wireless wifi toshiba satellite

Источник

how to get the IP of the wifi hotspot in Android?

As the title says. I’m trying to be able to get the IP of the wifi iface when it is configured as hotspot. Ideally, I would like to find something that works for all the phones. Of course, the WifiManager is useless when it comes to get info from the AP. Luckily, I’ve been able to get the IPs of all the interfaces by doing this:

public String getLocalIpAddress() < try < for (Enumerationen = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) < NetworkInterface intf = en.nextElement(); for (EnumerationenumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) < InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) < Log.d("IPs", inetAddress.getHostAddress() ); >> > > catch (SocketException ex) < Log.e(LOG_TAG, ex.toString()); >return null; > 
  • Filtering by the wifi iface display name: it’s not a good approach because the display name changes from one device to another (wlan0, eth0, wl0.1, etc).
  • Filtering by its mac address: almost work, but on some devices the hotspot iface does not have a MAC address ( iface.getHardwareAddress() returns null). so not a valid solution.

7 Answers 7

Here’s what I did to get the wifi hotspot ip:

public String getWifiApIpAddress() < try < for (Enumerationen = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) < NetworkInterface intf = en.nextElement(); if (intf.getName().contains("wlan")) < for (EnumerationenumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) < InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) < Log.d(TAG, inetAddress.getHostAddress()); return inetAddress.getHostAddress(); >> > > > catch (SocketException ex) < Log.e(TAG, ex.toString()); >return null; > 

This will give you the IP address of any wifi device, which means it’s not just for the hotspot. If you’re connected to another wifi network (meaning you’re not in hotspot mode), it’ll return an IP.

You should check if you are in AP mode first or not. You can use this class for that: http://www.whitebyte.info/android/android-wifi-hotspot-manager-class

Hi @ajma, Thanks for sharing this valuable code, this is working and give me ip address for both «WiFi simple router network» & » WiFi Tethering or hotspot».

This is not 100% correct. I’ve found out that the network interface name varies a lot. HTC Desire Z: wl0.1; Prestigio 3540: ap0; Nexus 5/Samsung DUOS: wlan0. On the other hand, in all cases there has been only one device listed (no loopback etc).

this code doesn’t work on some devices where the interface is named ap0. i suggest the following correction: if ((intf.getName().contains(«wlan»)) ||(intf.getName().contains(«ap»))) < on my phone there is a interface wlan0 but it has no inet address because the ip address is on the ap0. I also have the loopback interface in my case. when It is connected to a wifi router it uses the wlan0.

((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress 
private String getHotspotIPAddress() < int ipAddress = mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress; if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) < ipAddress = Integer.reverseBytes(ipAddress); >byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); String ipAddressString; try < ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress(); >catch (UnknownHostException ex) < ipAddressString = ""; >return ipAddressString; > 

Here is a possible solution that utilizes WiFiManager ConnectionInfo to find corresponding NetworkInterface .

If you just need the IP then you can use:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); 

I’m sorry but that’s not the solution. As I said before, WifiManager is useless when the iface is in AP mode. Android «thinks» that Wifi is disabled. On the other hand, I tried something similar to the solution you provide, but using the MAC address instead of the IP. But as I already pointed, it does not work. For some reason, the mac address of the wifi iface is null (in some devices).

Читайте также:  Free wi fi интернет

hello, my solution is open hotspot with show «fake dialog» to notify user, then dismiss when got ipaddress 🙂

When the Wifi is not setup as a hotspot, it has a name android-xx7632x324x32423 home when hotspot is turned on, that name is gone. Also the ip address changes.

So if you are able to get the Wifi config before enabling the hotspot, first of all you can use intf.getName() to get a reference to it.

Second, the ip changed, so if you know which interface the wifi is in CONNECTED mode, you can use that info to identify it later on after enabling the hotspot.

Below is some code I used for debugging. I just spit out everything I can find, make a huge mess then clean it up when I figured my problem out. GL

import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Collections; import android.net.ConnectivityManager; textStatus = (TextView) findViewById(R.id.textStatus); try < for (NetworkInterface intf : Collections.list(NetworkInterface.getNetworkInterfaces())) < for (InetAddress addr : Collections.list(intf.getInetAddresses())) < if (!addr.isLoopbackAddress())< textStatus.append("\n\n IP Address: " + addr.getHostAddress() ); textStatus.append("\n" + addr.getHostName() ); textStatus.append("\n" + addr.getCanonicalHostName() ); textStatus.append("\n\n" + intf.toString() ); textStatus.append("\n\n" + intf.getName() ); textStatus.append("\n\n" + intf.isUp() ); >> > > catch (Exception ex) < textStatus.append("\n\n Error getting IP address: " + ex.getLocalizedMessage() ); >connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); allInfo = connectivity.getAllNetworkInfo(); mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); textStatus.append("\n\n TypeName: " + mobileInfo.getTypeName()); textStatus.append("\n State: " + mobileInfo.getState()); textStatus.append("\n Subtype: " + mobileInfo.getSubtype()); textStatus.append("\n SubtypeName: " + mobileInfo.getSubtypeName()); textStatus.append("\n Type: " + mobileInfo.getType()); textStatus.append("\n ConnectedOrConnecting: " + mobileInfo.isConnectedOrConnecting()); textStatus.append("\n DetailedState: " + mobileInfo.getDetailedState()); textStatus.append("\n ExtraInfo: " + mobileInfo.getExtraInfo()); textStatus.append("\n Reason: " + mobileInfo.getReason()); textStatus.append("\n Failover: " + mobileInfo.isFailover()); textStatus.append("\n Roaming: " + mobileInfo.isRoaming()); textStatus.append("\n\n 0: " + allInfo[0].toString()); textStatus.append("\n\n 1: " + allInfo[1].toString()); textStatus.append("\n\n 2: " + allInfo[2].toString()); 

Источник

Get the name and IP of devices on a Wifi network

I know this question has been asked here but it didn’t get answered. I’m writing a simple Java Swing application in which I want to show the name and IP address of each and every device that is connected to my wireless network. I want to show this list in a JFrame . I searched a lot on the web but couldn’t find a way to achieve this. Please help me out Java masters! Thanks in advance!

«I know this question has been asked here but it didn’t get answered.» What question? Provide a link. It might not have been answered simply because there was no answer, and asking again won’t change that.

2 Answers 2

I found this code after looking a little bit. It works, but it is slow, and probably not the best way to do it, but it works.

import java.io.IOException; import java.net.InetAddress; public class NetworkPing < /** * JavaProgrammingForums.com */ public static void main(String[] args) throws IOException < InetAddress localhost = InetAddress.getLocalHost(); // this code assumes IPv4 is used byte[] ip = localhost.getAddress(); for (int i = 1; i else if (!address.getHostAddress().equals(address.getHostName())) < System.out.println(address + " machine is known in a DNS lookup"); >else < System.out.println(address + " the host address and host name are equal, meaning the host name could not be resolved"); >> > > 

Couple things to note, address.getHostAddress() returns the 192.168.0.xxx and address.getHostName() returns the name of the device like «Kevins-PC»

It’s a pretty simple piece of code, but I’ll walk through it real fast.

It starts off by getting your localhost IP address (which on a normal household network would be 192.168.0.xxx) and it stores that in a byte[] so it looks something like . Then it creates a for loop starting at 1 and going to 254 (because this code assumes a /24 subnet mask (255.255.255.0) but if its running a different subnet mask then it might not be 1-254). Then in the for loop it sets the third index of the ip to i. It then creates an InetAddress from that address. Then it tries to reach it in 1000 milliseconds (1 second), and if it succeeds then it prints the address and says its reachable. Else if the machine host address (the 192.168.0.xxx) does not equal the host name (like the name of your computer like Kevins-PC), then it says that the machine is known in a DNS lookup meaning it is found in a DNS lookup but it wasnt reachable (so its probably off or not connected, but it has been before), DNS is Domain Name Service. The DNS basically stores the information (your router probably does this). Finally, else it just says it couldn’t be resolved which means it wasnt reachable nor was it found looking in the DNS.

Читайте также:  Нужен интернет через wi fi

So if you run this and you just keep getting something like «192.168.0.5/192.168.0.5 the host address and host name are equal, meaning the host name could not be resolved» That means that your router (your local DNS) just isn’t storing the information OR those devices just choose not to submit their host name to the router, and that is why you will continually get that message. As far as I am aware, there isn’t a way around this because those device names literally aren’t stored

Источник

Android get IP-Address of a hotspot providing device

to get the IP-Address of the executing devices. That works fine if the device is connected to a «common» wlan-network as well as the device is connected to a wifi network which is hosted by an other android device via hotspot. If the device is not connected to any wifi network «0.0.0.0» is returned (correct). But if the device is hosting a wifi network by providing a hotspot the methode is still returning «0.0.0.0». How can I get the real IP-Address of a hotspot providing device «in its own wifi-network»? thx & regards

6 Answers 6

You’re almost right, the default IP address of hotspot is 192.168.43.1 (If device maker didn’t change.)

You can check the source code of Android framework (AOSP).

private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129"; private static final int USB_PREFIX_LENGTH = 24; // USB is 192.168.42.1 and 255.255.255.0 // Wifi is 192.168.43.1 and 255.255.255.0 // BT is limited to max default of 5 connections. 192.168.44.1 to 192.168.48.1 // with 255.255.255.0 private String[] mDhcpRange; private static final String[] DHCP_DEFAULT_RANGE = < "192.168.42.2", "192.168.42.254", "192.168.43.2", "192.168.43.254", "192.168.44.2", "192.168.44.254", "192.168.45.2", "192.168.45.254", "192.168.46.2", "192.168.46.254", "192.168.47.2", "192.168.47.254", "192.168.48.2", "192.168.48.254", >; 

Also, in the WifiStateMachine.java

private boolean startTethering(ArrayList available) < boolean wifiAvailable = false; checkAndSetConnectivityInstance(); String[] wifiRegexs = mCm.getTetherableWifiRegexs(); for (String intf : available) < for (String regex : wifiRegexs) < if (intf.matches(regex)) < InterfaceConfiguration ifcg = null; try < ifcg = mNwService.getInterfaceConfig(intf); if (ifcg != null) < /* IP/netmask: 192.168.43.1/255.255.255.0 */ ifcg.setLinkAddress(new LinkAddress( NetworkUtils.numericToInetAddress("192.168.43.1"), 24)); ifcg.setInterfaceUp(); mNwService.setInterfaceConfig(intf, ifcg); >> catch (Exception e) < loge("Error configuring interface " + intf + ", :" + e); return false; >if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) < loge("Error tethering on " + intf); return false; >mTetherInterfaceName = intf; return true; > > > // We found no interfaces to tether return false; > 

Therefore, the default value is 192.168.43.1 .

Источник

Оцените статью
Adblock
detector