解决linux下java代码获取不到本机ip地址

        今天在部署完预生产环境的时候发现一个问题,在linux下面java代码获取本机ip地址获取不到。但是我在测试环境上面是能够获取到的。先粘下获取本机ip的代码:

try{
    		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
    		InetAddress addr = null;
        	while (allNetInterfaces.hasMoreElements())
        	{
    	    	NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
    	    	//System.out.println(netInterface.getName());
    	    	Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
    	    	while (addresses.hasMoreElements())
    	    	{
    	    		InetAddress ipTmp = (InetAddress) addresses.nextElement();
    	    		if(ipTmp != null && ipTmp instanceof Inet4Address
    	    				&& ipTmp.isSiteLocalAddress()  
    	    				&& !ipTmp.isLoopbackAddress()  
    	    				&& ipTmp.getHostAddress().indexOf(":")==-1){
    	    			addr = ipTmp;
    	    		}
    	    	}
        	}
        	if(addr == null) throw new SystemException("获取本机ip异常");
        	return addr;
    	}catch(SocketException e){
    		e.printStackTrace();
    		throw new SystemException("获取本机ip异常");
    	}

这样的代码就不多解释了,网上一找一大把。 于是又把服务器的ip配置拿出来

似乎ip看起来也没有什么问题,没办法了只能一步步调试代码了,于是打上日志看看。

看到的日志服务器ip地址也能获取出来,但是结合上面的代码看有个条件是不满足的,isSiteLocalAddress()这个方法返回是false,按理说应该是true才对,这方法是javaAPI提供的,然后看下这个方法的源码:

/**
     * Utility routine to check if the InetAddress is a site local address.
     *
     * @return a <code>boolean</code> indicating if the InetAddress is
     * a site local address; or false if address is not a site local unicast address.
     * @since 1.4
     */
    public boolean isSiteLocalAddress() {
        // refer to RFC 1918
        // 10/8 prefix
        // 172.16/12 prefix
        // 192.168/16 prefix
        int address = holder().getAddress();
        return (((address >>> 24) & 0xFF) == 10)
            || ((((address >>> 24) & 0xFF) == 172)
                && (((address >>> 16) & 0xF0) == 16))
            || ((((address >>> 24) & 0xFF) == 192)
                && (((address >>> 16) & 0xFF) == 168));
    }

恍然大悟原来私有ip地址是有范围限制的,

对着服务器上面的ip一看,果然是不在这个范围内。这实施小哥把公有的ip拿来配成私有的,导致获取不到ip。把ip配置成私有ip的范围问题也就解决了。

猜你喜欢

转载自blog.csdn.net/weixin_40911297/article/details/83619766