【java】获取客户端访问的公网ip和归属地

  1 import com.alibaba.druid.support.json.JSONUtils;
  2 import org.thymeleaf.util.StringUtils;
  3 
  4 import javax.servlet.http.HttpServletRequest;
  5 import java.io.*;
  6 import java.net.*;
  7 import java.util.Map;
  8 
  9 /**
 10  * Created with IntelliJ IDEA.
 11  * User: xiaostudy
 12  * Date: 2019/7/18
 13  * Time: 19:58
 14  * Description: No Description
 15  */
 16 public class IpUtil {
 17 
 18     private static String urlStr = "http://ip.taobao.com/service/getIpInfo2.php";
 19     
 20     public static String getIpAddr(HttpServletRequest request) {
 21         String ipAddress;
 22         try {
 23             ipAddress = request.getHeader("x-forwarded-for");
 24             System.out.println("ipAddress:" + ipAddress);
 25             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 26                 ipAddress = request.getHeader("Proxy-Client-IP");
 27             }
 28             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 29                 ipAddress = request.getHeader("WL-Proxy-Client-IP");
 30             }
 31             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 32                 ipAddress = request.getHeader("HTTP_CLIENT_IP");
 33             }
 34             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 35                 ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
 36             }
 37             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 38                 ipAddress = request.getHeader("X-Real-IP");
 39             }
 40             if (null == ipAddress || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
 41                 ipAddress = request.getRemoteAddr();
 42                 if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
 43                     // 根据网卡取本机配置的IP
 44                     InetAddress inet = null;
 45                     try {
 46                         inet = InetAddress.getLocalHost();
 47                     } catch (UnknownHostException e) {
 48                         e.printStackTrace();
 49                     }
 50                     ipAddress = inet.getHostAddress();
 51                 }
 52             }
 53             // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
 54             if (ipAddress != null && ipAddress.length() > 15) {
 55                 if (ipAddress.indexOf(',') > 0) {
 56                     ipAddress = ipAddress.substring(0, ipAddress.indexOf(','));
 57                 }
 58             }
 59         } catch (Exception e) {
 60             ipAddress = "";
 61         }
 62 
 63         return ipAddress;
 64     }
 65 
 66     /**
 67      * 通过ip获取归属地
 68      *
 69      * @param ip
 70      * @return
 71      */
 72     public static String ipToBelonging(String ip) {
 73         System.out.println(getAddresses("ip=myip"));
 74         return getAddresses("ip=" + ip);
 75     }
 76 
 77     private static String getAddresses(String content) {
 78         String returnStr = getResult(urlStr, content, "utf-8");
 79         System.out.println(returnStr);
 80         if(!StringUtils.isEmpty(returnStr)) {
 81             Object parse = JSONUtils.parse(returnStr);
 82             if(parse instanceof Map) {
 83                 Map result = (Map) parse;
 84                 Object code = result.get("code");
 85                 Object data = result.get("data");
 86                 if(null == code || !"0".equals(code.toString()) || null == data) {
 87                     return "ip解析真实地址出错";
 88                 } else if(data instanceof Map) {
 89                     Map map = (Map) data;
 90                     String country = map.get("country").toString();
 91                     if("XX".equals(country)) {
 92                         return "内网地址";
 93                     }
 94                     String isp = map.get("isp").toString() + "-";
 95                     if("内网IP-".equals(isp)) {
 96                         isp = "";
 97                     }
 98                     String region = map.get("region").toString();
 99                     if("XX".equals(region)) {
100                         region = "";
101                     }
102                     String city = map.get("city").toString();
103                     if("XX".equals(city)) {
104                         city = "";
105                     }
106                     String county = map.get("county").toString();
107                     if("XX".equals(county)) {
108                         county = "";
109                     }
110                     return isp + country + region + city + county;
111                 } else {
112                     return "ip解析真实地址出错";
113                 }
114             }
115         }
116         return returnStr;
117     }
118 
119     /**
120      * @param urlStr   请求的地址
121      * @param content  请求的参数 格式为:name=xxx&pwd=xxx
122      * @param encoding 服务器端请求编码。如GBK,UTF-8等
123      * @return
124      */
125     private static String getResult(String urlStr, String content, String encoding) {
126         if(null == content) {
127             content = "";
128         }
129         if(StringUtils.isEmpty(encoding)) {
130             encoding = "utf-8";
131         }
132         URL url;
133         HttpURLConnection connection = null;
134         try {
135             url = new URL(urlStr);
136             connection = (HttpURLConnection) url.openConnection(); // 新建连接实例
137             connection.setConnectTimeout(2000); // 设置连接超时时间,单位毫秒
138             connection.setReadTimeout(2000); // 设置读取数据超时时间,单位毫秒
139             connection.setDoOutput(true); // 是否打开输出流 true|false
140             connection.setDoInput(true); // 是否打开输入流true|false
141             connection.setRequestMethod("POST"); // 提交方法POST|GET
142             connection.setUseCaches(false); // 是否缓存true|false
143             connection.connect(); // 打开连接端口
144             DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
145             out.writeBytes(content); // 写数据,也就是提交你的表单 name=xxx&pwd=xxx
146             out.flush(); // 刷新
147             out.close(); // 关闭输出流
148             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
149             // ,以BufferedReader流来读取
150             StringBuffer buffer = new StringBuffer();
151             String line = "";
152             while ((line = reader.readLine()) != null) {
153                 buffer.append(line);
154             }
155             reader.close();
156             return buffer.toString();
157         } catch (IOException e) {
158             e.printStackTrace();
159         } finally {
160             if (connection != null) {
161                 connection.disconnect(); // 关闭连接
162             }
163         }
164         return null;
165     }
166 }

猜你喜欢

转载自www.cnblogs.com/xiaostudy/p/11787386.html