0

我使用了获得 IP 地址的函数,如下所示:

public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()&&(inetAddress.getHostAddress().toString().matches(IPV4_REGEX))) {
                    return /*inetAddress.getHostName()+"~|~"+*/inetAddress.getHostAddress().toString();
                }

            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return null;
}   

但我注意到它获得了第一个appropriateIP 地址。在我插入 SIM 卡之前它工作正常。之后它获得手机的IP,而不是本地WiFi!所以我想知道如何排除这种情况?我只想获取 WiFi 路由器的本地 IP。非常感谢。

4

1 回答 1

1

使用下面的代码

WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
int ipAddress = myWifiInfo.getIpAddress();
System.out.println("WiFi address is " + android.text.format.Formatter.formatIpAddress(ipAddress));

并在清单文件中添加权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
于 2012-07-11T12:07:48.483 回答