展会信息港展会大全

android开发 获取手机IP地址的问题
来源:互联网   发布日期:2016-01-19 12:22:14   浏览:2695次  

导读:获取手机IP地址的代码:public static String getLocalIpAddress(){try{ for (EnumerationNetworkInterface en = NetworkInterface getNetworkInterfaces(); en hasMoreElements();) { NetworkInte ...

获取手机IP地址的代码:

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()) {

return inetAddress.getHostAddress().toString();

}

}

}

}catch (SocketException e) {

// TODO: handle exception

Utils.log("WifiPreference IpAddress---error-" + e.toString());

}

return null;

}

但是在4.0 下 会出现类似fe80::b607:f9ff:fee5:487e的IP地址, 这个是IPV6的地址,我们需要获得是的IPV4的地址,所以要在上诉代码中加一个判断

InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())

完整代码如下:

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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

return inetAddress.getHostAddress().toString();

}

}

}

}catch (SocketException e) {

// TODO: handle exception

Utils.log("WifiPreference IpAddress---error-" + e.toString());

}

return null;

}

赞助本站

人工智能实验室

相关热词: IP地址 android开发

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港