android获取网络地址通用方法

阅读更多

 

方法一:通过NetworkInterface获得所有网络设备的ip地址(包括ipv4和ipv6地址)
实现一:

String networkIp = "";
try {
    List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for(NetworkInterface iface : interfaces){
        if(iface.getDisplayName().equals("wlan0")){
            List addresses = Collections.list(iface.getInetAddresses());
            for(InetAddress address : addresses){
                if(address instanceof Inet4Address){
                    networkIp = address.getHostAddress();
                }
            }
        }
    }
} catch (SocketException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 

 

实现二:

String networkIp = "";
try {
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while(en.hasMoreElements()){
        NetworkInterface ni = en.nextElement();
        Log.i(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",ni.getDisplayName());
        Enumeration enIp = ni.getInetAddresses();
        while(enIp.hasMoreElements()){
            InetAddress inet = enIp.nextElement();
            if(!inet.isLoopbackAddress() && (inet instanceof Inet4Address)){
                networkIp = inet.getHostAddress().toString();
            }
        }
    }
    Log.i(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", "getIp end");
} catch (SocketException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

 

 
说明:
1.获取指定网络接口设备的地址,可通过NetworkInterface的getDisplayName()方法获取设备名称进行对比。
2.获取指定ipv4或者ipv6地址,可通过NetworkInterface的getInetAddress()方法获取到InetAddress列表进行遍历,对每个对象的类型进行判断即可(即instanceof Inet4Address或者Inet6Address)
3.推荐使用实现一,其实原理都是一样的,只因为实现一通过Collections的list方法将泛型Enumeration接口转换成List接口,代码更加简洁易懂。

 

方法二:通过WifiInfo获得wifi的ipv4地址

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String networkIp = "";
int hostAddress = (wifiInfo == null) ? 0 : wifiInfo.getIpAddress();
byte[] addressByte = {
        (byte)(0xff & hostAddress),
        (byte)(0xff & (hostAddress >> 8)),
        (byte)(0xff & (hostAddress >> 16)),
        (byte)(0xff & (hostAddress >> 24))
};
InetAddress inet = null;
try {
    inet = InetAddress.getByAddress(addressByte);
    networkIp = inet.getHostAddress().toString();
} catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

 
这种方法的局限性不言而喻,只能获取wifi的ipv4地址,且只能用于android设备,而NetworkInterface使用于所有可以使用java的设备上。

 

 

你可能感兴趣的:(network,ipv4,ipv6)