android获取网络地址通用方法

 

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

String networkIp = "";
try {
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for(NetworkInterface iface : interfaces){
        if(iface.getDisplayName().equals("wlan0")){
            List<InetAddress> 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<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while(en.hasMoreElements()){
        NetworkInterface ni = en.nextElement();
        Log.i(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",ni.getDisplayName());
        Enumeration<InetAddress> 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的设备上。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值