获取本地的IP地址(内网)

时间:2024-11-28 12:05:32

方法一

    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();
Log.e("XXX", inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}

方法二

    private static void getIpAddress() {
new Thread() {
@Override
public void run() {
super.run();
Socket socket = null;
try {
socket = new Socket("www.baidu.com", 80);// 只有这个可以
// 但是这个内网地址有没有外网的地址呢?
Log.e("XXX", "socket : "
+ socket.getLocalAddress().toString() + "\n");
} catch (Exception e) {
e.printStackTrace(); } finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
}

以上方法获取到的地址是大都是内网的IP地址,如需获取公网的IP地址,需要访问:

www.ip138.com才可以,然后解析文本即可。