• java获取hostIp和hostName


    InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:


    static InetAddress[] getAllByName(String host)
    static InetAddress getByAddress(byte[] addr)
    static InetAddress getByAddress(String host,byte[] addr)
    static InetAddress getByName(String host)
    static InetAddress getLocalHost()

    java获取本地ip信息时getLocalHost(),匹配C:WindowsSystem32drivershosts中的数据,如果是windows系统可以直接调用getLocalHost()获得。但是如果是多个网口取值的数据未知。

    但是linux系统则会找到localhost.localdomain:127.0.0.1

    所以想获得真正的ip4地址,需要从网口的地址进行筛选

     1     public static InetAddress getInetAddress() throws SocketException{
     2         Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
     3         InetAddress ipHost = null;
     4         while (allNetInterfaces.hasMoreElements()) {
     5             NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
     6             Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
     7             while (addresses.hasMoreElements()) {
     8                 ipHost = (InetAddress) addresses.nextElement();
     9                 if (ipHost != null && ipHost instanceof Inet4Address) {
    10                     System.out.println("本机的HOSTIP = " + ipHost.getHostAddress());
    11                     System.out.println("本机的HOSTNAME = " + ipHost.getHostName());
    12                     return ipHost;
    13                 }
    14             }
    15         }
    16         return ipHost;
    17     }

    问题来了:

    如果主机有多个ipv4地址该如何处理?

  • 相关阅读:
    双端队列广搜
    多源bfs
    leetcode刷题-67二进制求和
    leetcode刷题-66加一
    leetcode刷题-64最小路径和
    leetcode刷题-62不同路径2
    leetcode刷题-62不同路径
    leetcode刷题-61旋转链表
    leetcode刷题-60第k个队列
    leetcode刷题-59螺旋矩阵2
  • 原文地址:https://www.cnblogs.com/huluyisheng/p/6867370.html
Copyright © 2020-2023  润新知