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

java获取机器名及所有网卡IP

2016-11-09 17:19 411 查看
获取机器名:

public String getLocalHostName() {
String hostName;
try {
InetAddress addr = InetAddress.getLocalHost();
hostName = addr.getHostName();
} catch (Exception ex) {
hostName = "";
}
return hostName;
}


获取IP(多个网卡时获取了多个IP):

public List<String> getNetworkAddress() {
List<String> result = new ArrayList<String>();
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> addresses=ni.getInetAddresses();
while(addresses.hasMoreElements()){
ip = addresses.nextElement();
if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
result.add(ip.getHostAddress());
}
}
}
return result;
} catch (Exception e) {
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: