如何在Java中确定WiFi网络接口名称?
由于您说您正在Android上进行开发,因此请使用以下内容:
WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
System.out.println(wifiInfo.getSSID());
这将返回您的WIFI名称。
您需要将此权限添加到您的清单中。
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements())
{
NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
System.out.println(networkInterface.getDisplayName());
}
如果您只想选择 WLAN 接口,也许您需要通过 JNI 来实现,否则您可以检查名称中是否出现了“wlan”(例如 eth0、eth1 等)。我不建议仅依赖这种命名约定。
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements())
{
NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
if(networkInterface.getName().startsWith("wlan")) {
System.out.println(networkInterface.getDisplayName());
}
}
public static String getInterfaceName() {
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/net/wireless")));
// skip header
reader.readLine();
reader.readLine();
// read first interesting line
String ifLine = reader.readLine();
reader.close();
// extract interface name
String ifName = ifLine.substring(0, ifLine.indexOf(':'));
return ifName.trim();
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}