如何用 Java 获取系统 IP

2025-01-19 08:21:19
推荐回答(2个)
回答1:

import java.net.*;

public class Test6 {

public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress ia=null;
try {
ia=ia.getLocalHost();

String localname=ia.getHostName();
String localip=ia.getHostAddress();
System.out.println("本机名称是:"+ localname);
System.out.println("本机的ip是 :"+localip);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

回答2:

public static InetAddress getSystemLocalIp() throws UnknownHostException{
InetAddress inet=null;
String osname=getSystemOSName();
try {
//针对window系统
if(osname.equalsIgnoreCase("Windows XP")){
inet=getWinLocalIp();
//针对linux系统
}else if(osname.equalsIgnoreCase("Linux")){
inet=getUnixLocalIp();
}
if(null==inet){
throw new UnknownHostException("主机的ip地址未知");
}
}catch (SocketException e) {
logger.error("获取本机ip错误"+e.getMessage());
throw new UnknownHostException("获取本机ip错误"+e.getMessage());
}
return inet;
}