android4.0以上系统获取IP v4地址
在android2.3以下的系统中,可以使用如下的代码来获取Android系统的本地IP地址:
[java]
private String getLocalIPAddress() throws SocketException{
for(Enumeration<NetworkInte易做图ce> en = NetworkInte易做图ce.getNetworkInte易做图ces();en.hasMoreElements();){
NetworkInte易做图ce intf = en.nextElement(); www.zzzyk.com
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的地址,可以这么更改:
[java]
private String getLocalIPAddress() throws SocketException{
for(Enumeration<NetworkInte易做图ce> en = NetworkInte易做图ce.getNetworkInte易做图ces();en.hasMoreElements();){
NetworkInte易做图ce intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress = enumIpAddr.nextElement();
if(!inetAddress.isLoopbackAddress() && <strong>(inetAddress instanceof Inet4Address)</strong>){
return inetAddress.getHostAddress().toString();
}
}
}
return "null";
}
需要import的包有:
import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.NetworkInte易做图ce;
补充:移动开发 , Android ,