java中获取本地IP地址

2025-02-25 05:04:01
推荐回答(5个)
回答1:

方法如下:
方法一,使用CMD命令:
public static String getLocalIPForCMD(){
StringBuilder sb = new StringBuilder();
String command = "cmd.exe /c ipconfig | findstr IPv4";
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = br.readLine()) != null){
line = line.substring(line.lastIndexOf(":")+2,line.length());
sb.append(line);
}
br.close();
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
方法二,使用Java方法:
public static String getLocalIPForJava(){
StringBuilder sb = new StringBuilder();
try {
Enumeration en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
Enumeration enumIpAddr = intf.getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
&& inetAddress.isSiteLocalAddress()) {
sb.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException e) { }
return sb.toString();
}

回答2:

java.net.InetAddress.getLocalHost().getHostAddress()

回答3:

try {
System.out.println(java.net.InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

回答4:

这个情况很多了,比哪机器有双网卡的时候,或者你机器配了vpn的时候。。

回答5:

当本地有多张网卡时可以有多个IP地址,