Java获取本地IP异常问题

yzmm
620 阅读

获取本地IP往往只需要:InetAddress.getLocalHost().getHostAddress()就行了,但是今天在测试的时候发现这个方法并不怎么靠谱。服务器配置有问题导致无法通过主机名获取IP地址从而抛出了一个UnknowHostException。临时的程序解决办法是假设getLocalHost异常则用NetworkInterface方法获取IP:

public InetAddress getLocalHostLANAddress() throws UnknownHostException {
	    try {
	        InetAddress candidateAddress = null;
	        for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
	            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
	            for (Enumeration<?> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
	                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
	                if (!inetAddr.isLoopbackAddress()) {
	                    if (inetAddr.isSiteLocalAddress()) {
	                        return inetAddr;
	                    }
	                    else if (candidateAddress == null) {
	                        candidateAddress = inetAddr;
	                    }
	                }
	            }
	        }
	        if (candidateAddress != null) {
	            return candidateAddress;
	        }
	        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
	        if (jdkSuppliedAddress == null) {
	            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
	        }
	        return jdkSuppliedAddress;
	    }
	    catch (Exception e) {
	        UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
	        unknownHostException.initCause(e);
	        throw unknownHostException;
	    }
	}
    public InetAddress getLocalHost(){
    	InetAddress inetAddress = null;
    	try {
    		inetAddress = InetAddress.getLocalHost();
		} catch (Exception e) {
			try {
				inetAddress = getLocalHostLANAddress();
			} catch (UnknownHostException e1) {
				ClientLogger.clog(e);
			}
		}
    	return inetAddress;
    }

评论 (3)

depy
园长,能不能帮我看看我下的一个flex bbs系统源代码,搞了很长时间允许不了??谢谢阿
yzmm
啊?叫什么名字

发表评论