java如何获取本地ip地址

avatar
作者
筋斗云
阅读量:0

在Java中获取本地IP地址可以通过以下方式之一:

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

这两种方法都可以获取本地IP地址,第一种方法使用了InetAddress类的getLocalHost()方法,直接获取本地IP地址,而第二种方法通过遍历所有网络接口和对应的InetAddress来获取本地IP地址。

广告一刻

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