1. 程式人生 > >Java獲取本地伺服器Ip的方法

Java獲取本地伺服器Ip的方法

@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;
}