in Android, Code

Android: How to obtain the WiFi’s corresponding NetworkInterface

Let’s say for some odd reason in the world you do need to get the corresponding NetworkInterface object of the Wifi on your android, in my case I needed to have my WiFi device send multicast packets, and I wanted my MulticastSocket to only send packets through the WiFi device (not 3g, or maybe even ethernet). The android API does not provide functionality to know what “NetworkInterface” your WiFi is using.

Here’s a solution proven in tens of different android phones, seems to work 100%.

[java]
public static NetworkInterface getWifiNetworkInterface(WifiManager manager) {

Enumeration<NetworkInterface> interfaces = null;
try {
//the WiFi network interface will be one of these.
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
return null;
}

//We’ll use the WiFiManager’s ConnectionInfo IP address and compare it with
//the ips of the enumerated NetworkInterfaces to find the WiFi NetworkInterface.

//Wifi manager gets a ConnectionInfo object that has the ipAdress as an int
//It’s endianness could be different as the one on java.net.InetAddress
//maybe this varies from device to device, the android API has no documentation on this method.
int wifiIP = manager.getConnectionInfo().getIpAddress();

//so I keep the same IP number with the reverse endianness
int reverseWifiIP = Integer.reverseBytes(wifiIP);

while (interfaces.hasMoreElements()) {

NetworkInterface iface = interfaces.nextElement();

//since each interface could have many InetAddresses…
Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress nextElement = inetAddresses.nextElement();
int byteArrayToInt = byteArrayToInt(nextElement.getAddress(),0);

//grab that IP in byte[] form and convert it to int, then compare it
//to the IP given by the WifiManager’s ConnectionInfo. We compare
//in both endianness to make sure we get it.
if (byteArrayToInt == wifiIP || byteArrayToInt == reverseWifiIP) {
return iface;
}
}
}

return null;
}

public static final int byteArrayToInt(byte[] arr, int offset) {
if (arr == null || arr.length – offset < 4)
return -1;

int r0 = (arr[offset] & 0xFF) << 24;
int r1 = (arr[offset + 1] & 0xFF) << 16;
int r2 = (arr[offset + 2] & 0xFF) << 8;
int r3 = arr[offset + 3] & 0xFF;
return r0 + r1 + r2 + r3;
}
[/java]

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.