您的位置:首页 > 编程语言 > Java开发

Java获取本地服务器Ip的方法

2017-10-25 17:43 573 查看
@SuppressWarnings("rawtypes")
private static String getHostIp() {
Enumeration allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
InetAddress ip = null;
String hostIP = "";
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
hostIP = ip.getHostAddress();
System.out.println("本机的IP = " + ip.getHostAddress());
}
}
}
return hostIP;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: