Home  >  Article  >  Java  >  Java gets the IP addresses of all network cards on this machine (ipv4)

Java gets the IP addresses of all network cards on this machine (ipv4)

巴扎黑
巴扎黑Original
2016-12-28 17:55:052295browse

/**
* 获取机器所有网卡的IP(ipv4)
* @return
*/
public static List<String> getLocalIP() {
List<String> ipList = new ArrayList<String>();
InetAddress ip = null;
try {
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
// 遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
if (null == ip || "".equals(ip)) {
continue;
}
String sIP = ip.getHostAddress();
if(sIP == null || sIP.indexOf(":") > -1) {
continue;
}
ipList.add(sIP);
System.out.println(sIP);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ipList;
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn