动态获取本机的ip地址和hostName

代码:

public class logTest {
    private static String localAddress;
    private static String hostName;
    public static void main(String[] args) throws UnknownHostException, SocketException {
//        InetAddress ip = InetAddress.getLocalHost();
//        String hostName = ip.getHostName();
//        String hostAddress = ip.getHostAddress();
//        System.out.println("ip:"+ip+"\n"+"hostname:"+hostName+"\n"+"hostAddress:"+hostAddress);
        System.out.println("=========================");
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        ArrayList<String> ips = new ArrayList<String>();
        ArrayList<String> hostnames = new ArrayList<>();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            //获取网络接口的InetAddresses信息
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (!address.isLoopbackAddress()&& !address.isLinkLocalAddress() && address instanceof Inet4Address) {
                   //获取ip地址字符串
                    ips.add(address.getHostAddress());
                    hostnames.add(address.getHostName());

                }
            }
        }
        System.out.println("ips:"+ips+"\n hostnames:"+hostnames);
        if (!ips.isEmpty()) {
            for (String ip : ips) {
                if (!ip.startsWith("127.0") && !ip.startsWith("192.168")) {
                    localAddress = ip;
                    break;
                }
            }

            if (localAddress == null) {
                // 取第一个
                localAddress = ips.get(0);
            }
        } else {
            localAddress = InetAddress.getLocalHost().getHostAddress();
        }
        System.out.println("====================");
        System.out.println(localAddress);
    }


}

运行结果
动态获取本机的ip地址和hostName_第1张图片

你可能感兴趣的:(tcp/ip,java)