欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 获取服务器IP,本地IP

程序员文章站 2022-03-26 10:37:41
...

以前把程式发布的Server IP都写成一个IP-Config 文件中。 为了避免发布程式每次去更改IP-Config ,或是在不同Server上发布程式更改IP-Config。决定把IP-Config 的MXL中的信息融入到JAVA程式中。即自动获取取服务器IP。看了很多function,比如

 

String serverIP = ServletActionContext.getRequest().getServerName(); 

 

String serverIP  = request.getLocalAddr();

 

等方法,获取的都是127.0.0.1/loaclhost这样让人无奈的地址,比较推荐以下两个function,简单易懂:而且做过测试,在Apache反向代理,多Server的负载均衡(轮询),等都可正常运行。

 

获取服务器IP

 public String  getServerIp(){
    	try {
			Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces
						.nextElement();
				ip = (InetAddress) ni.getInetAddresses().nextElement();
				SERVER_IP = ip.getHostAddress();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
						&& ip.getHostAddress().indexOf(":") == -1) {
					SERVER_IP = ip.getHostAddress();
					break;
				} else {
					ip = null;
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    
      return SERVER_IP;
    }

 

 获取本地IP

    方法一:

public static String getLocalIP(){   
		InetAddress addr = null;   
		            try {
						addr = InetAddress.getLocalHost();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}   
		        
		        byte[] ipAddr = addr.getAddress();   
		        String ipAddrStr = "";   
		        for (int i = 0; i < ipAddr.length; i++) {   
		            if (i > 0) {   
		                ipAddrStr += ".";   
		            }   
		            ipAddrStr += ipAddr[i] & 0xFF;   
		        }   
		        //System.out.println(ipAddrStr);   
		                return ipAddrStr;   
		}  

  方法二:

public static String getHostIp(){  
		InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(null == addr){  
            return null;  
        }  
        String ip = addr.getHostAddress(); //get the ip address  
        return ip;  
    }