/** (第一种方法)
* 这是最简单的方法,但也容易出问题,获取的IP地址可能是:127.0.0.1 或其他,而并不是客户端的真实IP。
*/
public static void main(String[] args) {
try{
// 获取计算机名
String name = InetAddress.getLocalHost().getHostName();
// 获取IP地址
String ip = InetAddress.getLocalHost().getHostAddress();
System.out.println("计算机名:"+name);
System.out.println("IP地址:"+ip);
}
catch (UnknownHostException e){
System.out.println("异常:" + e);
e.printStackTrace();
}
}
/** (第二种方法)
* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
*
* @param request
* @return
*/
public final static String getIpAddress(HttpServletRequest request) {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
try {
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 = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ip;
}
注意:第二种方法获取的地址可能是0:0:0:0:0:0:0:1 在URL上的不用localhost即可
/** (第三种方法)
* 直接通过运行cmd获取ip地址
*
* @return
*/
public static String getLocalIPForCMD() {
StringBuilder sb = new StringBuilder();
String command = "cmd.exe /c ipconfig | findstr IPv4";
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
line = line.substring(line.lastIndexOf(":") + 2, line.length());
sb = new StringBuilder();
sb.append(line);
}
br.close();
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}