检测Android上的wifi IP地址?

时间:2011-11-02 03:20:12

标签: android networking wifi

我需要确定Android设备是否已连接到Wifi,如果是,请获取其Wifi IP地址。

我知道如何使用ConnectivityManager来确定活动网络是否是Wifi网络,我知道如何使用java.net.NetworkInterface迭代可用的网络接口并获取其IP地址。

我不知道如何确定哪个IP地址属于Wifi网络,如果找到多个地址。有什么建议吗?

感谢。

3 个答案:

答案 0 :(得分:45)

public String getIpAddr() {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ip = wifiInfo.getIpAddress();

   String ipString = String.format(
   "%d.%d.%d.%d",
   (ip & 0xff),
   (ip >> 8 & 0xff),
   (ip >> 16 & 0xff),
   (ip >> 24 & 0xff));

   return ipString;
}

请注意:您需要在android.permission.INTERNET android.permission.ACCESS_WIFI_STATE中添加AndroidManifest.xml<user-permission/>以访问代码。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

答案 1 :(得分:3)

请尝试此代码。

ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//To fetch the state of the Wi-Fi network in the device
Boolean isWifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); 

WifiManager wifiMgr = (WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE); 
WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); 

//To fetch the name of the Wi-Fi network to which the device is connected
String wifiName = wifiInfo.getSSID(); 

答案 2 :(得分:1)

static final int IP_ADDRESS_LENGTH = 32;

  public static Integer getSystemWifiIpAddress(Context context)
  {
    WifiManager wManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wInfo = wManager.getConnectionInfo();

    int ipAddress = wInfo.getIpAddress();
    if (ipAddress == 0)
      return null;
    return ipAddress;
  }