zoukankan      html  css  js  c++  java
  • 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地址该如何处理?

  • 相关阅读:
    【交换】
    【数字对】
    【改造二叉树】
    【Begin】
    100以内所有质数的输出
    位运算符、|和||、&和&&的区别
    linux中vim编辑器三种模式及常用命令的使用
    静态代码块、构造代码块和构造函数的执行顺序
    字符乱码出现的原因及解决办法
    Springcloud-微服务
  • 原文地址:https://www.cnblogs.com/huluyisheng/p/6867370.html
Copyright © 2011-2022 走看看