wifi network interface name
I am developing an android app in which phone connects to a wifi network or acts as a wifi access point. I need to get the correct interface name.When phone connects to a wifi network on a mac, interface name is ‘eth0’ and when it acts as an access point it is ‘wl0.1’. I find this using NetworkInterface.getNetworkInterfaces() which lists all interfaces. I want to get active wifi interface name only.Any help on this?
3 Answers 3
NetworkInterface has getHardwareAddress for returning the hardware (MAC) address of the interface. WifiInfo , representing the current state of Wi-Fi (obtained by WifiManager.getConnectionInfo ) has getMacAddress method. Just use the latter to find your Wi-Fi interace.
Remember that when comparing the addresses, you should convert them to common format as getHardwareAddress returns array of bytes while getMacAddress returns string with colon-separated hex values.
As far is I know, there are two ways to obtain the interface name of the Wi-Fi adaptor on an Android device, using Java. Via either the Wi-Fi interface’s:
Once you have either piece of information, you can use NetworkInterface to figure out the rest.
Option #1, via MAC address, is likely the best option. MAC addresses are are always available, even when a device is not on a network. It might actually be desirable to some people to get the interface name when the device is not connected to a network. MAC addresses never change, and if so rarely. So doing it through the Wi-Fi adaptor’s MAC address promises to be more robust.
Here is an example on how to get the Wi-Fi interface name through its MAC address. It is an expansion on Xion‘s original answer.
protected String wifiInterfaceName(final Context context) < // Get WiFi interface's MAC address as a BigInteger. WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String wifiMacString = wifiInfo.getMacAddress(); byte[] wifiMacBytes = macAddressToByteArray(wifiMacString); BigInteger wifiMac = new BigInteger(wifiMacBytes); String result = null; try < ListnetworkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface currentInterface : networkInterfaces) < byte[] hardwareAddress = currentInterface.getHardwareAddress(); if (hardwareAddress != null) < BigInteger currentMac = new BigInteger(hardwareAddress); if (currentMac.equals(wifiMac)) < result = currentInterface.getName(); break; >> > > catch (SocketException ex) < Log.e("WifiGet", "Socket excpetion: " + ex.getMessage()); >return result; > protected byte[] macAddressToByteArray(String macString) < String[] mac = macString.split("[:\\s-]"); byte[] macAddress = new byte[6]; for (int i = 0; i < mac.length; i++) < macAddress[i] = Integer.decode("0x" + mac[i]).byteValue(); >return macAddress; >
Option #2, via IP address, is pretty well explained in the question section of: Get Wifi Interface name on Android. There are a few things to be aware of when trying to get the Wi-Fi interface name by IP address:
- It only works when the device is connected to a Wi-Fi network.
- IP addresses change so there is a very small chance your operation will fail if you catch the device changing IP address.
- This one I am still trying to figure out. But there might be issues with the endianness of various devices and the result from WifiInfo getIpAddress(). Again, I’m not sure. All I know for certain is that I have to reverse byte order in order for me to get the actual IP address.
The following example is based on the question part of Get Wifi Interface name on Android
protected String wifiInterfaceName2(final Context context) < WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) < ipAddress = Integer.reverseBytes(ipAddress); >byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); String result; try < InetAddress addr = InetAddress.getByAddress(bytes); NetworkInterface netInterface = NetworkInterface.getByInetAddress(addr); result = netInterface.getName(); >catch (UnknownHostException ex) < LOG.error("Unknown host.", ex); result = null; >catch (SocketException ex) < LOG.error("Socket exception.", ex); result = null; >return result; >
Please keep in mind that both code segments have been provided as examples only. Make sure to clean up the code, add error handling, and test if you plan on using either in production.
Oh, and don’t forget to add the proper permissions to your AndroidManifest.xml as well. I think they are something along the lines of:
Also, these examples will only work on an actual device. No Wi-Fi on the emulators.
How to get current Wi-Fi network id in android?
This example demonstrates How to get current Wi-Fi network id in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
In the above code, we have taken text view to show WIFI network id.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.widget.TextView; public class MainActivity extends AppCompatActivity < TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); textView.setText("" + wifiInfo.getNetworkId()); >@Override protected void onStop() < super.onStop(); >@Override protected void onResume() < super.onResume(); >>
Step 4 − Add the following code to androidManifest.xml
Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
How to get name of wifi-network out of android using android API?
I thought that I should use NetworkInterface::getDisplayName. I got some name, but this name is different that this name which I can see, when I choosing to which network I want to connect.
4 Answers 4
WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); String name = wifiInfo.getSSID();
public String getWifiName(Context context) < WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (manager.isWifiEnabled()) < WifiInfo wifiInfo = manager.getConnectionInfo(); if (wifiInfo != null) < DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()); if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) < return wifiInfo.getSSID(); >> > return null; >
This (mix and match of various answers from Marakana and others) will simultaneously get everything you want to extract from:
- all wifi routers in range
- connected wifi router
- all stored wifi networks (on your device)
public String getCurrentSsid(Context context) < String ssid = null; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) < final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) < //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) < ssid = connectionInfo.getSSID(); >// Get WiFi status MARAKANA WifiInfo info = wifiManager.getConnectionInfo(); String textStatus = ""; textStatus += "\n\nWiFi Status: " + info.toString(); String BSSID = info.getBSSID(); String MAC = info.getMacAddress(); List results = wifiManager.getScanResults(); ScanResult bestSignal = null; int count = 1; String etWifiList = ""; for (ScanResult result : results) < etWifiList += count++ + ". " + result.SSID + " : " + result.level + "\n" + result.BSSID + "\n" + result.capabilities +"\n" + "\n=======================\n"; >Log.v(TAG, "from SO: \n"+etWifiList); // List stored networks List configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) < textStatus+= "\n\n" + config.toString(); >Log.v(TAG,"from marakana: \n"+textStatus); > return ssid; >
DISCLAIMER: while this is working code, not pseudo code, its only purpose is to illustrate the methods for data extraction from wifi connections and it should be adapted (and cleaned) before use.
Get Android WiFi «net.hostname» from code
When an Android device connects to a wifi AP, it identifies itself with a name like: android_cc1dec12345e6054 How can that string be obtained from within an Android app? Not for the purpose of changing it, just for readout. EDIT:
This is a screenshot of my router’s web interface, showing a list of all connected devices. Note the two Android devices on the list — How can that string be read from Java code running on the device?
Not trying to get the router’s SSID — Trying to get the android device’s hostname string, which it somehow provides to the router.
7 Answers 7
Building off of @Merlevede’s answer, here’s a quick and dirty way to get the property. It’s a private API, so it’s subject to change, but this code hasn’t been modified since at least Android 1.5 so it’s probably safe to use.
import android.os.Build; import java.lang.reflect.Method; /** * Retrieves the net.hostname system property * @param defValue the value to be returned if the hostname could * not be resolved */ public static String getHostName(String defValue) < try < Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); return getString.invoke(null, "net.hostname").toString(); >catch (Exception ex) < return defValue; >>
You weren’t kidding about that «Private API». java.lang.IllegalAccessException: access to method denied
Strange. I’m on a Nexus 5 running 4.4.2, so it shouldn’t be any different. Can you try with the edited change? ( setAccessible(true) )
Just for other Android newbie’s — the class Method is java.lang.reflect.Method and the class Build is android.os.Build .
This will not work in Android O — Querying the net.hostname system property produces a null result. — Ref: developer.android.com/preview/behavior-changes.html
I don’t know if this helps but here I go.
From a unix shell (you can download any Terminal app in Google Play), you can get the hostname by typing
Of course this is not what you want. but. on the other hand, here is information on how to execute a unix command from java. Maybe by combining these two you get what you’re looking for.
Thanks Merlevede, that helped. Further investigation shows that «net.hostname» is a deep Java SystemProperty, not exposed in the Android SDK. It can be made available through reflection, though: stackoverflow.com/questions/2641111/…
Use the NetworkInterface object to enumerate the interfaces and get the canonical host name from the interfaces’ InetAddress . Since you want the wifi name, as a shortcut you can query for wlan0 directly and if that fails you can enumerate them all like this:
import android.test.InstrumentationTestCase; import android.util.Log; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class NetworkInterfaceTest extends InstrumentationTestCase < private static final String TAG = NetworkInterfaceTest.class.getSimpleName(); public void testNetworkName() throws Exception < Enumerationit_ni = NetworkInterface.getNetworkInterfaces(); while (it_ni.hasMoreElements()) < NetworkInterface ni = it_ni.nextElement(); Enumerationit_ia = ni.getInetAddresses(); if (it_ia.hasMoreElements()) < Log.i(TAG, "++ NI: " + ni.getDisplayName()); while (it_ia.hasMoreElements()) < InetAddress ia = it_ia.nextElement(); Log.i(TAG, "-- IA: " + ia.getCanonicalHostName()); Log.i(TAG, "-- host: " + ia.getHostAddress()); >> > > >
That will give you an output like this:
TestRunner﹕ started: testNetworkName ++ NI: lo -- IA: ::1%1 -- host: ::1%1 -- IA: localhost -- host: 127.0.0.1 ++ NI: p2p0 -- IA: fe80::1234:1234:1234:1234%p2p0 -- host: fe80::1234:1234:1234:1234%p2p0 ++ NI: wlan0 -- IA: fe80::1234:1234:1234:1234%wlan0 -- host: fe80::1234:1234:1234:1234%wlan0 -- IA: android-1234567812345678
Tip: if InetAddress.getCanonicalHostName().equals(InetAddress.getHostAddress()) you can ignore it as it's not a "real" name.