InetAddress

这个方法不是很稳定

  1. String hostAddress = InetAddress.getLocalHost().getHostAddress(); // 192.168.1.15

NetworkInterface

比较稳定,遍历网卡,获取IP列表。

  1. import org.springframework.util.Assert;
  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.net.SocketException;
  5. import java.util.*;
  6. /**
  7. * 网络攻击类
  8. */
  9. public class NetUtil {
  10. /**
  11. * 获取IP列表
  12. * @return
  13. * @throws SocketException
  14. */
  15. public static HashSet<String> getLocalIpAddr() throws SocketException {
  16. HashSet<String> ipList = new HashSet<>();
  17. Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
  18. while (interfaces.hasMoreElements()) {
  19. NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
  20. Enumeration ipAddrEnum = ni.getInetAddresses();
  21. while (ipAddrEnum.hasMoreElements()) {
  22. InetAddress addr = (InetAddress) ipAddrEnum.nextElement();
  23. if (addr.isLoopbackAddress()) {
  24. continue;
  25. }
  26. String ip = addr.getHostAddress();
  27. //skip the IPv6 addr
  28. if (ip.contains(":")) {
  29. continue;
  30. }
  31. // 去掉以1结尾的
  32. if (ip.endsWith(".1")) {
  33. continue;
  34. }
  35. ipList.add(ip);
  36. }
  37. }
  38. Assert.isTrue(ipList.size() > 0, "没有获取到IP");
  39. return ipList;
  40. }
  41. public static void main(String args[]) throws SocketException {
  42. HashSet<String> localIpAddr = getLocalIpAddr();
  43. System.out.println(localIpAddr);
  44. }
  45. }