InetAddress
这个方法不是很稳定
String hostAddress = InetAddress.getLocalHost().getHostAddress(); // 192.168.1.15
NetworkInterface
比较稳定,遍历网卡,获取IP列表。
import org.springframework.util.Assert;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
/**
* 网络攻击类
*/
public class NetUtil {
/**
* 获取IP列表
* @return
* @throws SocketException
*/
public static HashSet<String> getLocalIpAddr() throws SocketException {
HashSet<String> ipList = new HashSet<>();
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
Enumeration ipAddrEnum = ni.getInetAddresses();
while (ipAddrEnum.hasMoreElements()) {
InetAddress addr = (InetAddress) ipAddrEnum.nextElement();
if (addr.isLoopbackAddress()) {
continue;
}
String ip = addr.getHostAddress();
//skip the IPv6 addr
if (ip.contains(":")) {
continue;
}
// 去掉以1结尾的
if (ip.endsWith(".1")) {
continue;
}
ipList.add(ip);
}
}
Assert.isTrue(ipList.size() > 0, "没有获取到IP");
return ipList;
}
public static void main(String args[]) throws SocketException {
HashSet<String> localIpAddr = getLocalIpAddr();
System.out.println(localIpAddr);
}
}