-
在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;
相关文章
- Get IP Address in Android 4.0+
- Get the client's IP address in socket.io
- Genymotion虚拟机启动时get no IP address的解决方法汇总
- Get Local IP Address in Swift
- Unable to construct api.Node object for kubelet: can't get ip address of node master.example.com: lookup master.example.com on : no such host
- Linux环境下Jmeter 报错:Unable to get local host IP address