Linux下获得本机IP(非127.0.0.1)

在Linux下用InetAddress.getLocalHost()方法获取本机IP地址,
得到的结果总是:127.0.1.1。
原来这个是etc/hosts文件中的配置,并非网卡的IP地址。

可用代码如下:注:该代码只适合在Liunx,在Windows不支持;

/**
 * IP工具类
 * @author lyh
 * @version 2012-7-5
 * @see IpGetter
 * @since
 */
public class IpGetter
{
    /**
     * 日志
     */
    private static final Logger log = Logger.getLogger(IpGetter.class);

    /**
     * 单网卡名称
     */
    private static final String NETWORK_CARD = "eth0";

    /**
     * 绑定网卡名称
     */
    private static final String NETWORK_CARD_BAND = "bond0";

    /**
     * 
     * Description: 得到本机名<br>
     * @return 
     * @see
     */
    public static String getLocalHostName()
    {
        try
        {
            InetAddress addr = InetAddress.getLocalHost();
            return addr.getHostName();
        }
        catch (Exception e)
        {
            log.error("IpGetter.getLocalHostName出现异常!异常信息:" + e.getMessage());
            return "";
        }
    }

    /**
     * Description: linux下获得本机IPv4 IP<br>
     * @return 
     * @see
     */
    public static String getLocalIP()
    {
        String ip = "";
        try
        {
            Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>)NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements())
            {
                NetworkInterface ni = e1.nextElement();

                //单网卡或者绑定双网卡
                if ((NETWORK_CARD.equals(ni.getName()))
                    || (NETWORK_CARD_BAND.equals(ni.getName())))
                {
                    Enumeration<InetAddress> e2 = ni.getInetAddresses();
                    while (e2.hasMoreElements())
                    {
                        InetAddress ia = e2.nextElement();
                        if (ia instanceof Inet6Address)
                        {
                            continue;
                        }
                        ip = ia.getHostAddress();
                    }
                    break;
                }
                else
                {
                    continue;
                }
            }
        }
        catch (SocketException e)
        {
            log.error("IpGetter.getLocalIP出现异常!异常信息:" + e.getMessage());
        }
        return ip;
    }

}

  

posted @ 2019-10-19 15:14  古语云  阅读(842)  评论(0编辑  收藏  举报