一个比较简单的工具方法
public 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();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
}
return null;
}
本文介绍了一个简单的Java工具方法,用于获取设备的本地IP地址。通过遍历网络接口并检查非回环地址,该方法能有效地找到并返回当前设备的IP地址。
8838

被折叠的 条评论
为什么被折叠?



