web123456

Java to obtain native 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 { /** * Get the local IP * * @return List<String> * @author Yunshen Xiaomai */ 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(); // Remove 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("Native IP: " + ip); } } }