天天看點

java 用戶端外網ip_Java擷取用戶端公網IP

目前總結了兩種擷取用戶端的公網IP方法。

方法一:通過第三方網站進行擷取()

public static void main(String[] args){

String ip = "";

String chinaz = "http://ip.chinaz.com";

StringBuilder inputLine = new StringBuilder();

String read = "";

URL url = null;

HttpURLConnection urlConnection = null;

BufferedReader in = null;

try {

url = new URL(chinaz);

urlConnection = (HttpURLConnection) url.openConnection();

in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));

while((read=in.readLine())!=null){

inputLine.append(read+"\r\n");

}

//System.out.println(inputLine.toString());

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(in!=null){

try {

in.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

Pattern p = Pattern.compile("\\

(.*?)\\");

Matcher m = p.matcher(inputLine.toString());

if(m.find()){

String ipstr = m.group(1);

ip = ipstr;

//System.out.println(ipstr);

}

System.out.println(ip);

}

第二種方法:通過http請求頭部擷取(别人測試ok,但本人測試隻能擷取到本機的内網IP)

package com.ehking.commons.web.utils;

import org.apache.commons.lang.StringUtils;

import java.net.InetAddress;

import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

private IpUtils() {

}

public static String getIpAddr(HttpServletRequest request) {

if (request == null) {

return "unknown";

}

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("X-Forwarded-For");

}

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("X-Real-IP");

}

if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

try {

ip = request.getRemoteAddr();

}catch (Throwable e){

e.printStackTrace();

}

if(StringUtils.isBlank(ip)||"127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){

//根據網卡取本機配置的IP

InetAddress inet=null;

try {

inet = InetAddress.getLocalHost();

} catch (UnknownHostException e) {

e.printStackTrace();

}

if(null != inet){

ip= inet.getHostAddress();

}

}

}

if(StringUtils.isNotBlank(ip) && ip.contains(",")){

ip=ip.split(",")[0];

}

return StringUtils.isNotBlank(ip)?ip.trim():null;

}

}