您的位置:首页 > 移动开发 > Android开发

android4.0以上系统获取IP v4地址

2012-11-19 14:50 399 查看
在android2.3以下的系统中,可以使用如下的代码来获取Android系统的本地IP地址:

private String getLocalIPAddress() throws SocketException{
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();
}
}
}
return "null";
}


但是,在android4.0以上系统中,上面的代码仅能够返回一个ipv6的地址,如果需要获取ip v4的地址,可以这么更改:

private String getLocalIPAddress() throws SocketException{
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 instanceof Inet4Address)){
return inetAddress.getHostAddress().toString();
}
}
}
return "null";
}


需要import的包有:

import java.net.InetAddress;

import java.net.Inet4Address;

import java.net.InetSocketAddress;

import java.net.NetworkInterface;

【更多精彩】

[原]adb push时提示read-only file system
[原]Android NDK开发环境的搭建,无需Cygwin
[原]Android去广告
[原]TIOBE 2012年12月份编程语言排行榜:Objective-C走在再次称为年度语言的路上
[原]Android系统的无广告软件
[原]DLP Coder:C#写的一个用于编辑DLP投影机程序的编辑器
[原]Freeplot: MATLAB来帮你手动画图
[原]adb push时提示read-only file system
[原]编写Android的exe可执行文件并运行
[原]Android系统的Socket多线程编程实例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: