zoukankan      html  css  js  c++  java
  • [转] java获取hostIp和hostName

    【From】 https://www.cnblogs.com/huluyisheng/p/6867370.html

    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地址,需要从网口的地址进行筛选:

    public static InetAddress getInetAddress() throws SocketException{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ipHost = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ipHost = (InetAddress) addresses.nextElement();
                    if (ipHost != null && ipHost instanceof Inet4Address) {
                        System.out.println("本机的HOSTIP = " + ipHost.getHostAddress());
                        System.out.println("本机的HOSTNAME = " + ipHost.getHostName());
                        return ipHost;
                    }
                }
            }
            return ipHost;
        }

    问题来了:

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

  • 相关阅读:
    yii模板中常用变量总结
    Yii CDbCriteria的常用方法总结
    Yii框架Yiiapp()的理解
    Yii 中比较常用的rules验证规则记录
    c++,opencv播放视频
    python--输入一组无序的数,排序
    python入门,猜数
    关于爬楼梯问题的斐波那契数列
    获取文件名字,路劲中的某一部分信息
    简单帧差法
  • 原文地址:https://www.cnblogs.com/pekkle/p/9784953.html
Copyright © 2011-2022 走看看