Java获取本机IP
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; @Slf4j public class TestInetAddress { /** * 获取当前服务器ip */ @Test public void testGetIp() throws Exception { // 获取本机名和ip InetAddress localHost = InetAddress.getLocalHost(); log.info(localHost.toString()); log.info(localHost.getHostName()); log.info(localHost.getHostAddress()); InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); log.info(loopbackAddress.toString()); InetAddress localHostV4 = Inet4Address.getLocalHost(); log.info(localHostV4.toString()); // 10:55:53.227 [main] INFO part2.tools.InetAddress.TestInetAddress - NJXDGD02600/10.100.80.54 // 10:55:53.231 [main] INFO part2.tools.InetAddress.TestInetAddress - NJXDGD02600 // 10:55:53.231 [main] INFO part2.tools.InetAddress.TestInetAddress - 10.100.80.54 // 10:55:53.231 [main] INFO part2.tools.InetAddress.TestInetAddress - localhost/127.0.0.1 // 10:55:53.231 [main] INFO part2.tools.InetAddress.TestInetAddress - NJXDGD02600/10.100.80.54 } /** * 获取本机所有ip地址 */ @Test public void testAllIP() throws SocketException { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface networkinterface = en.nextElement(); Enumeration<InetAddress> inetAddresses = networkinterface.getInetAddresses(); if (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); // 去除非IPv4的内容 if (inetAddress instanceof Inet4Address) { String hostAddress = inetAddress.getHostAddress(); // 去除127.0.0.1 if (!hostAddress.equals("127.0.0.1")) { log.info(inetAddress.toString()); log.info("{}/{}", inetAddress.getHostName(), inetAddress.getHostAddress()); log.info("------------"); } } } // 10:52:54.022 [main] INFO part2.tools.InetAddress.TestInetAddress - /10.100.80.54 // 10:52:54.031 [main] INFO part2.tools.InetAddress.TestInetAddress - NJXDGD02600.Shein-inc.com/10.100.80.54 } } }