java获取本机IP地址,非127.0.0.1

时间:2023-03-09 06:21:57
java获取本机IP地址,非127.0.0.1

综合了网上找的代码,整理的,Windows和Linux都可以用。


  1. private static String getHostIp(){
  2. try{
  3. Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
  4. while (allNetInterfaces.hasMoreElements()){
  5. NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
  6. Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
  7. while (addresses.hasMoreElements()){
  8. InetAddress ip = (InetAddress) addresses.nextElement();
  9. if (ip != null
  10. && ip instanceof Inet4Address
  11. && !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
  12. && ip.getHostAddress().indexOf(":")==-1){
  13. System.out.println("本机的IP = " + ip.getHostAddress());
  14. return ip.getHostAddress();
  15. }
  16. }
  17. }
  18. }catch(Exception e){
  19. e.printStackTrace();
  20. }
  21. return null;
  22. }