本文目錄一覽:
- 1、java如何獲取用戶真實的ip
- 2、java如何獲取公網ip,有通過路由
- 3、java IP查詢方法
- 4、java怎麼獲取請求的ip
- 5、JAVA如何限制用戶IP地址?
- 6、如何用 Java 獲取系統 IP
java如何獲取用戶真實的ip
1、如果服務器如果沒有採用反向代理,而且客戶端沒有用正向代理的話,那麼可以獲取客戶端的真實IP地址request.getRemoteAddr()
2、如果服務器如果沒有採用反向代理,而且客戶端有用正向代理的話,那麼通過request.getRemoteAddr()獲取客戶端的IP地址是客戶端 的代理服務器的地址,並不是客戶端的真實地址,
3、如果客戶端使用的是多層代理的話,服務器獲得的客戶端地址是客戶端的最外圍代理服務器的地址如果服務器如果採用反向代理服務器,不管客戶端採用的是何種方式訪問服務器。
//獲得客戶端真實IP地址的方法一:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader(“x-forwarded-for”) == null) {
return request.getRemoteAddr();
}
return request.getHeader(“x-forwarded-for”);
}
//獲得客戶端真實IP地址的方法二:
public 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;
}
java如何獲取公網ip,有通過路由
如果要通過路由器,不同的路由器的獲取方法不一樣。通用的做法是通過 HttpClient 在百度上搜索關鍵字 ip, 然後提取出公網ip。
代碼如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class App {
// 獲取網頁源碼
static String httpGet(String url) {
StringBuffer buffer = new StringBuffer();
try {
URLConnection conn = new URL(url).openConnection();
conn.addRequestProperty(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36”);
try (InputStream inputStream = conn.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);) {
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line).append(System.lineSeparator());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
String html = httpGet(“”);
// 提出IP
Pattern pattern = Pattern.compile(“span\\sclass=\”c-gap-right\”本機IP:nbsp;([^]+)/span”);
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
String ip = matcher.group(1);
System.out.println(ip);
}
}
}
java IP查詢方法
Java編程查詢IP地址歸屬地,可以調用淘寶提供的service查詢,並且解析http請求返回的json串,代碼如下:
package getAddressByIp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;
public class GetAddressByIp
{
/**
*
* @param IP
* @return
*/
public static String GetAddressByIp(String IP){
String resout = “”;
try{
String str = getJsonContent(“”+IP);
System.out.println(str);
JSONObject obj = JSONObject.fromObject(str);
JSONObject obj2 = (JSONObject) obj.get(“data”);
String code = (String) obj.get(“code”);
if(code.equals(“0”)){
resout = obj2.get(“country”)+”–” +obj2.get(“area”)+”–” +obj2.get(“city”)+”–” +obj2.get(“isp”);
}else{
resout = “IP地址有誤”;
}
}catch(Exception e){
e.printStackTrace();
resout = “獲取IP地址異常:”+e.getMessage();
}
return resout;
}
public static String getJsonContent(String urlStr)
{
try
{// 獲取HttpURLConnection連接對象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 設置連接屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod(“GET”);
// 獲取相應碼
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return “”;
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = “”;
// ByteArrayOutputStream相當於內存輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 將輸入流轉移到內存輸出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 將內存流轉換為字符串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
java怎麼獲取請求的ip
java獲取外網ip地址方法:
public class Main {
public static void main(String[] args) throws SocketException {
System.out.println(Main.getRealIp());
}
public static String getRealIp() throws SocketException {
String localip = null;// 本地IP,如果沒有配置外網IP則返回它
String netip = null;// 外網IP
EnumerationNetworkInterface netInterfaces =
NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外網IP
while (netInterfaces.hasMoreElements() !finded) {
NetworkInterface ni = netInterfaces.nextElement();
EnumerationInetAddress address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress()
!ip.isLoopbackAddress()
ip.getHostAddress().indexOf(“:”) == -1) {// 外網IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress()
!ip.isLoopbackAddress()
ip.getHostAddress().indexOf(“:”) == -1) {// 內網IP
localip = ip.getHostAddress();
}
}
}
if (netip != null !””.equals(netip)) {
return netip;
} else {
return localip;
}
}
}
JAVA如何限制用戶IP地址?
java web中限制訪問的ip,主要是使用session的getRemortIP(HttpServletRequest)方法,如下代碼:
/**
*
* @param request
* @return
*
* 功 能 :得到用戶Ip地址
*/
public static String getRemortIP(HttpServletRequest request) {
if (request.getHeader(“x-forwarded-for”) == null) {
return request.getRemoteAddr();
}
return request.getHeader(“x-forwarded-for”);
}
調用
String ip = getRemortIP(HttpServletRequest);
if(ip == “127.0.0.1”){
System.out.print(“禁止訪問”);
}
Hr完整項目中 — common.jsp 得到網址
%
//路徑
String path = request.getContextPath();
// request 保存
request.setAttribute(“path”,path);
%
如何用 Java 獲取系統 IP
import java.net.*;
public class Test6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress ia=null;
try {
ia=ia.getLocalHost();
String localname=ia.getHostName();
String localip=ia.getHostAddress();
System.out.println(“本機名稱是:”+ localname);
System.out.println(“本機的ip是 :”+localip);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/244753.html