---
title: "Java 获取服务器IP，本地IP"
author: "提烟而过"
date: "2011-04-23T11:32:42Z"
tags: []
categories: ["编程语言"]
slug: "java-ip-ip"
draft: false
lastmod: "2011-04-23T11:35:38Z"
id: 1013302
url: "https://kata520-java.iteye.com/blog/1013302"
---

以前把程式发布的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的负载均衡(轮询),等都可正常运行。

```
 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;
    }
```

 

```
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;   
		}  
```