Java获取IP工具类

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NetworkUtil {

    public static String getNetworkAddress() {
        List result = new ArrayList<>();
        Enumeration netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
                        result.add(ip.getHostAddress());
                    }
                }
            }
            if (result.isEmpty()) return "";
            return result.get(0);
        } catch (Exception e) {
            return "";
        }
    }

    public static void main(String[] args) {
        String networkAddress = getNetworkAddress();
        System.out.println(getNetworkAddress());
    }
}

 

你可能感兴趣的:(Java获取IP工具类)