-
admin
2024-06-21 d76bbaa8a9a70124045dc4c9753e5a868ac4e7d2
提交 | 用户 | 时间
e57a89 1 package com.jcdm.main.util;
2
3 import javax.servlet.http.HttpServletRequest;
4 import java.net.InetAddress;
5 import java.net.UnknownHostException;
6
7 /**
8  * ip工具类
9  *
10  * @author fengshuonan
11  * @Date 2018/9/27 上午10:47
12  */
13 public class IpInfoUtils {
14
15     /**
16      * 获取客户端IP地址
17      */
18     public static String getIpAddr(HttpServletRequest request) {
19         String ip = request.getHeader("x-forwarded-for");
20         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
21             ip = request.getHeader("Proxy-Client-IP");
22         }
23         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
24             ip = request.getHeader("WL-Proxy-Client-IP");
25         }
26         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
27             ip = request.getRemoteAddr();
28             if (ip.equals("127.0.0.1")) {
29                 //根据网卡取本机配置的IP
30                 InetAddress inet = null;
31                 try {
32                     inet = InetAddress.getLocalHost();
33                 } catch (UnknownHostException e) {
34                     e.printStackTrace();
35                 }
36                 ip = inet.getHostAddress();
37             }
38         }
39         // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
40         if (ip != null && ip.length() > 15) {
41             if (ip.indexOf(",") > 0) {
42                 ip = ip.substring(0, ip.indexOf(","));
43             }
44         }
45
46         if ("0:0:0:0:0:0:0:1".equals(ip)) {
47             ip = "127.0.0.1";
48         }
49
50         return ip;
51     }
52
53     /**
54      * 获取客户端主机名称
55      */
56     public static String getHostName() {
57         try {
58             return InetAddress.getLocalHost().getHostName();
59         } catch (UnknownHostException e) {
60         }
61         return "未知";
62     }
63 }