Java 获取客户端请求IP地址(公网ip)
2021-01-27 19:16
标签:ipaddr cas port nbsp out try array ips code Java 获取客户端请求IP地址(公网ip) 标签:ipaddr cas port nbsp out try array ips code 原文地址:https://www.cnblogs.com/w-yu-chen/p/12843059.htmlpackage sdcncsi.ict.util.redis;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description
* @Author
* @Date
*/
public class IPUtil {
/**
*
* @Description:获取客户端的IP
* @author
* @date 2020/05/07 10:51
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
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.getRemoteAddr();
}
return ip;
}
/**
* @Description:获取客户端外网ip 此方法要接入互联网才行,内网不行
* @Author:
* @Date:2020/05/07 10:51
**/
public static String getPublicIp() {
try {
String path = "http://www.net.cn/static/customercare/yourip.asp";// 要获得html页面内容的地址
URL url = new URL(path);// 创建url对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 打开连接
conn.setRequestProperty("contentType", "GBK"); // 设置url中文参数编码
conn.setConnectTimeout(5 * 1000);// 请求的时间
conn.setRequestMethod("GET");// 请求方式
InputStream inStream = conn.getInputStream();
// readLesoSysXML(inStream);
BufferedReader in = new BufferedReader(new InputStreamReader(
inStream, "GBK"));
StringBuffer buffer = new StringBuffer();
String line = "";
// 读取获取到内容的最后一行,写入
while ((line = in.readLine()) != null) {
buffer.append(line);
}
List
文章标题:Java 获取客户端请求IP地址(公网ip)
文章链接:http://soscw.com/index.php/essay/47893.html