-
在android2.3以下的系统中,可以使用如下的代码来获取Android系统的本地IP地址:
[java]
private String getLocalIPAddress() throws SocketException{
for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf = en.nextElement(); www.2cto.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<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() && <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.NetworkInterface;