Android获取wifi的IP地址

public static String getWifiIp()
{
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if(!wifiManager.isWifiEnabled())
    {
        return null;
    }

    WifiInfo wi = wifiManager.getConnectionInfo();
    Log.e(TAG, "getWifiIp() wi="+wi);
    if (wi == null)
    {
        return null;
    }
    //获取32位整型IP地址
    int ipAdd=wi.getIpAddress();
    Log.e(TAG, "getWifiIp() ipAdd="+ipAdd);
    if (ipAdd == 0)
    {
        return null;
    }
    //把整型地址转换成“*.*.*.*”地址
    String ip=intToIp(ipAdd);
    Log.e(TAG, "getWifiIp() ip="+ip);

    if (ip == null || ip.startsWith("0"))
    {
        return null;
    }
    return ip;
}

private static String intToIp(int i)
{
    return (i & 0xFF ) + "." +
            ((i >> 8 ) & 0xFF) + "." +
            ((i >> 16 ) & 0xFF) + "." +
            ( i >> 24 & 0xFF) ;
}

猜你喜欢

转载自blog.csdn.net/LikeSidehu/article/details/81027226