java中获取本地IP地址
发布网友
发布时间:2022-04-24 16:58
我来回答
共5个回答
热心网友
时间:2022-05-19 13:27
方法如下:
方法一,使用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<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
Enumeration<InetAddress> 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();
}
热心网友
时间:2022-05-19 14:45
java.net.InetAddress.getLocalHost().getHostAddress()
热心网友
时间:2022-05-19 16:19
try {
System.out.println(java.net.InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
热心网友
时间:2022-05-19 18:11
这个情况很多了,比哪机器有双网卡的时候,或者你机器配了*的时候。。
热心网友
时间:2022-05-19 20:19
当本地有多张网卡时可以有多个IP地址,