java 获取本机ip地址

    xiaoxiao2021-03-25  22

    import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class IpUtils { public static void main(String[] args) { String localIp = ""; try { localIp = getFirstNonLoopbackAddress(true,false); } catch (SocketException e) { // TODO Auto-generated catch block System.out.println("获取的ip失败!"); e.printStackTrace(); } System.out.println("获取的ip:" + localIp); } /** * 取得本机一个非回环地址IPv4 IP * * @param isIpv4 * @param isIPv6 * @return * @throws SocketException */ public static String getFirstNonLoopbackAddress(boolean isIpv4, boolean isIPv6) throws SocketException { // 获得本机的所有网络接口 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface nif = networkInterfaces.nextElement(); // 获得与该网络接口绑定的 IP 地址,一般只有一个 Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (!addr.isLoopbackAddress()) { // Ipv4 if (addr instanceof Inet4Address) { if (isIPv6) { continue; } return addr.getHostAddress(); } // Ipv6 if (addr instanceof Inet6Address) { if (isIpv4) { continue; } return addr.getHostAddress(); } } } } return null; } }
    转载请注明原文地址: https://ju.6miu.com/read-200261.html

    最新回复(0)