Java 获取本机IP
注意:代码中去除了127.0.0.1
获取本机所有IP
package com.airport.controller;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class TestController {
/**
* 获取本机IP
*
* @return List<String>
* @author 云深小麦
*/
private static List<String> getIp() {
List<String> result = new ArrayList<>();
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface netInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ip = addresses.nextElement();
if (ip instanceof Inet4Address) {
String hostAddress = ip.getHostAddress();
// 去除127.0.0.1
if (!hostAddress.equals("127.0.0.1")) {
result.add(hostAddress);
}
}
}
}
} catch (Exception e) {
return null;
}
return result;
}
public static void main(String[] args) {
for (String ip : getIp()) {
System.out.println("本机IP: " + ip);
}
}
}
main方法输出
本机IP: 192.168.31.12