
java中获取当前服务器地址主要使用到InetAddress这个类
public static void main(String[] args) {
try {
//用 getLocalHost() 方法创建的InetAddress的对象
InetAddress address = InetAddress.getLocalHost();
System.out.println(address.getHostName());//主机名
System.out.println(address.getCanonicalHostName());//主机别名
System.out.println(address.getHostAddress());//获取IP地址
System.out.println("==============="); //用域名创建 InetAddress对象
InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");
//获取的是该网站的ip地址,如果我们所有的请求都通过nginx的,所以这里获取到的其实是nginx服务器的IP地址
System.out.println(address1.getHostName());//www.wodexiangce.cn
System.out.println(address1.getCanonicalHostName());//124.237.121.122
System.out.println(address1.getHostAddress());//124.237.121.122
System.out.println("==============="); //用IP地址创建InetAddress对象
InetAddress address2 = InetAddress.getByName("220.181.111.188");
System.out.println(address2.getHostName());//220.181.111.188
System.out.println(address2.getCanonicalHostName());//220.181.111.188
System.out.println(address2.getHostAddress());//220.181.111.188
System.out.println("==============="); //根据主机名返回其可能的所有InetAddress对象
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
for (InetAddress addr : addresses) {
System.out.println(addr);
//www.baidu.com/220.181.111.188
//www.baidu.com/220.181.112.244
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
如果使用了反向代理,这种获取方式显然是不准确的,我们采用的方法是新建一个java类,里面配的是当前服务器的IP地址(也就是说这个类在每个节点服务器上部署的是不同的),程序里用的话直接获取这个工具类就可以了,虽然方法有点笨,但是解决问题了。
public class CommonServerIP {
/**
* #######################################################################
* ###############这个类主要是保存常用的一些固定的服务器IP#####################
* #######################################################################
*/
public static String CURRENT_SERVER="124.237.121.46";//当前服务器的ip地址
}
根据HttpServletRequest对象获取ip
public String getIpAddress(HttpServletRequest request) {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
try {
String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}