java如何获取linux的ip地址

avatar
作者
猴君
阅读量:0

在Java中获取Linux系统的IP地址可以通过以下几种方法:

  1. 使用InetAddress类:
import java.net.InetAddress; import java.net.UnknownHostException;  public class GetIPAddress {     public static void main(String[] args) {         try {             InetAddress address = InetAddress.getLocalHost();             System.out.println("IP Address: " + address.getHostAddress());         } catch (UnknownHostException e) {             e.printStackTrace();         }     } } 
  1. 使用NetworkInterface类:
import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration;  public class GetIPAddress {     public static void main(String[] args) {         try {             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();             while (interfaces.hasMoreElements()) {                 NetworkInterface networkInterface = interfaces.nextElement();                 Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();                 while (addresses.hasMoreElements()) {                     InetAddress address = addresses.nextElement();                     if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {                         System.out.println("IP Address: " + address.getHostAddress());                     }                 }             }         } catch (Exception e) {             e.printStackTrace();         }     } } 

这两种方法都可以获取Linux系统的IP地址,其中第一种方法是获取本地主机的IP地址,而第二种方法则是获取所有网络接口的IP地址。根据你的需求选择合适的方法获取IP地址即可。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!