这篇是碰巧用到这个功能,,总结下,借鉴了大佬的代码,文末注明来源
package com.jk.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
public class IpUtil {
/**
* 获取当前网络ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Test {
public static void main(String[] args) {
try {
//根据域名查找主机的IP地址(由于可能有多个服务器,ip地址并不是唯一的,要想获取准确的,还需要获取所有的地址才行)
InetAddress inetAddress=InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress);//结果:14.215.177.38
//反向查找主机名
InetAddress byName = InetAddress.getByName("113.105.245.103");
System.out.println("反向查找主机名: "+byName.getHostName());//如果没有主机名,会返回IP地址
//得到主机的所有地址
InetAddress[] inetAddresses=InetAddress.getAllByName("www.taobao.com");
for (InetAddress address : inetAddresses) {
System.out.println(address);
}
//getLocalHost获取当前主机名和IP地址
InetAddress me = InetAddress.getLocalHost();//得到主机名/IP地址 的形式
System.out.println(me);//如果电脑没有联网,会返回127.0.0.1
System.out.println(me.getHostName());//得到主机名
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
参考:https://blog.csdn.net/sxj_world/article/details/79107413
https://blog.csdn.net/shenhaiyushitiaoyu/article/details/84061999