java 獲取服務(wù)器真實(shí)IP的實(shí)例
java 獲取服務(wù)器真實(shí)IP的實(shí)例
前言:
根據(jù)操作系統(tǒng)的不同,獲取的結(jié)果不同,故需要區(qū)分系統(tǒng),分別獲取
實(shí)現(xiàn)代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;
/**
* 常用工具類(lèi)
*
* @author 席紅蕾
* @date 2016-09-27
* @version 1.0
*/
public class WebToolUtils {
/**
* 獲取本地IP地址
*
* @throws SocketException
*/
public static String getLocalIP() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLinuxLocalIp();
}
}
/**
* 判斷操作系統(tǒng)是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 獲取本地Host名稱(chēng)
*/
public static String getLocalHostName() throws UnknownHostException {
return InetAddress.getLocalHost().getHostName();
}
/**
* 獲取Linux下的IP地址
*
* @return IP地址
* @throws SocketException
*/
private static String getLinuxLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
System.out.println(ipaddress);
}
}
}
}
}
} catch (SocketException ex) {
System.out.println("獲取ip地址異常");
ip = "127.0.0.1";
ex.printStackTrace();
}
System.out.println("IP:"+ip);
return ip;
}
/**
* 獲取用戶(hù)真實(shí)IP地址,不使用request.getRemoteAddr();的原因是有可能用戶(hù)使用了代理軟件方式避免真實(shí)IP地址,
*
* 可是,如果通過(guò)了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP值,究竟哪個(gè)才是真正的用戶(hù)端的真實(shí)IP呢?
* 答案是取X-Forwarded-For中第一個(gè)非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
*
* 用戶(hù)真實(shí)IP為: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 向指定URL發(fā)送GET方法的請(qǐng)求
*
* @param url
* 發(fā)送請(qǐng)求的URL
* @param param
* 請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
* @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
*/
// public static String sendGet(String url, String param) {
// String result = "";
// BufferedReader in = null;
// try {
// String urlNameString = url + "?" + param;
// URL realUrl = new URL(urlNameString);
// // 打開(kāi)和URL之間的連接
// URLConnection connection = realUrl.openConnection();
// // 設(shè)置通用的請(qǐng)求屬性
// connection.setRequestProperty("accept", "*/*");
// connection.setRequestProperty("connection", "Keep-Alive");
// connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;
// MSIE 6.0; Windows NT 5.1;SV1)");
// // 建立實(shí)際的連接
// connection.connect();
// // 獲取所有響應(yīng)頭字段
// Map<String, List<String>> map = connection.getHeaderFields();
// // 遍歷所有的響應(yīng)頭字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// // 定義 BufferedReader輸入流來(lái)讀取URL的響應(yīng)
// in = new BufferedReader(new
// InputStreamReader(connection.getInputStream()));
// String line;
// while ((line = in.readLine()) != null) {
// result += line;
// }
// } catch (Exception e) {
// System.out.println("發(fā)送GET請(qǐng)求出現(xiàn)異常!" + e);
// e.printStackTrace();
// }
// // 使用finally塊來(lái)關(guān)閉輸入流
// finally {
// try {
// if (in != null) {
// in.close();
// }
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// return result;
// }
/**
* 向指定 URL 發(fā)送POST方法的請(qǐng)求
*
* @param url
* 發(fā)送請(qǐng)求的 URL
* @param param
* 請(qǐng)求參數(shù),請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
* @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
*/
public static void sendPost(String pathUrl, String name, String pwd, String phone, String content) {
// PrintWriter out = null;
// BufferedReader in = null;
// String result = "";
// try {
// URL realUrl = new URL(url);
// // 打開(kāi)和URL之間的連接
// URLConnection conn = realUrl.openConnection();
// // 設(shè)置通用的請(qǐng)求屬性
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// // 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行
// conn.setDoOutput(true);
// conn.setDoInput(true);
// // 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流
// out = new PrintWriter(conn.getOutputStream());
// // 發(fā)送請(qǐng)求參數(shù)
// out.print(param);
// // flush輸出流的緩沖
// out.flush();
// // 定義BufferedReader輸入流來(lái)讀取URL的響應(yīng)
// in = new BufferedReader(
// new InputStreamReader(conn.getInputStream()));
// String line;
// while ((line = in.readLine()) != null) {
// result += line;
// }
// } catch (Exception e) {
// System.out.println("發(fā)送 POST 請(qǐng)求出現(xiàn)異常!"+e);
// e.printStackTrace();
// }
// //使用finally塊來(lái)關(guān)閉輸出流、輸入流
// finally{
// try{
// if(out!=null){
// out.close();
// }
// if(in!=null){
// in.close();
// }
// }
// catch(IOException ex){
// ex.printStackTrace();
// }
// }
// return result;
try {
// 建立連接
URL url = new URL(pathUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// //設(shè)置連接屬性
httpConn.setDoOutput(true);// 使用 URL 連接進(jìn)行輸出
httpConn.setDoInput(true);// 使用 URL 連接進(jìn)行輸入
httpConn.setUseCaches(false);// 忽略緩存
httpConn.setRequestMethod("POST");// 設(shè)置URL請(qǐng)求方法
String requestString = "客服端要以以流方式發(fā)送到服務(wù)端的數(shù)據(jù)...";
// 設(shè)置請(qǐng)求屬性
// 獲得數(shù)據(jù)字節(jié)數(shù)據(jù),請(qǐng)求數(shù)據(jù)流的編碼,必須和下面服務(wù)器端處理請(qǐng)求流的編碼一致
byte[] requestStringBytes = requestString.getBytes("utf-8");
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type", " application/x-www-form-urlencoded");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長(zhǎng)連接
httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0");
httpConn.setRequestProperty("Upgrade-Insecure-Requests", "1");
httpConn.setRequestProperty("account", name);
httpConn.setRequestProperty("passwd", pwd);
httpConn.setRequestProperty("phone", phone);
httpConn.setRequestProperty("content", content);
// 建立輸出流,并寫(xiě)入數(shù)據(jù)
OutputStream outputStream = httpConn.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.close();
// 獲得響應(yīng)狀態(tài)
int responseCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == responseCode) {// 連接成功
// 當(dāng)正確響應(yīng)時(shí)處理數(shù)據(jù)
StringBuffer sb = new StringBuffer();
String readLine;
BufferedReader responseReader;
// 處理響應(yīng)流,必須與服務(wù)器響應(yīng)流輸出的編碼一致
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 執(zhí)行一個(gè)HTTP POST請(qǐng)求,返回請(qǐng)求響應(yīng)的HTML
*
* @param url
* 請(qǐng)求的URL地址
* @param params
* 請(qǐng)求的查詢(xún)參數(shù),可以為null
* @return 返回請(qǐng)求響應(yīng)的HTML
*/
public static void doPost(String url, String name, String pwd, String phone, String content) {
// 創(chuàng)建默認(rèn)的httpClient實(shí)例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創(chuàng)建httppost
HttpPost httppost = new HttpPost(url);
// 創(chuàng)建參數(shù)隊(duì)列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("account", name));
formparams.add(new BasicNameValuePair("passwd", pwd));
formparams.add(new BasicNameValuePair("phone", phone));
formparams.add(new BasicNameValuePair("content", content));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關(guān)閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上就是java 獲取服務(wù)去的IP的實(shí)例,如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Java將Object轉(zhuǎn)換為數(shù)組的代碼
這篇文章主要介紹了Java將Object轉(zhuǎn)換為數(shù)組的情況,今天在使用一個(gè)別人寫(xiě)的工具類(lèi),這個(gè)工具類(lèi),主要是判空操作,包括集合、數(shù)組、Map等對(duì)象是否為空的操作,需要的朋友可以參考下2022-09-09
Mybatis之動(dòng)態(tài)sql標(biāo)簽的使用
這篇文章主要介紹了Mybatis之動(dòng)態(tài)sql標(biāo)簽的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時(shí)遇到的結(jié)點(diǎn)為空的問(wèn)題詳解
這篇文章主要介紹了Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時(shí)遇到的結(jié)點(diǎn)為空的問(wèn)題及解決辦法,需要的朋友們可以學(xué)習(xí)下。2019-09-09
Java實(shí)現(xiàn)聯(lián)系人管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)聯(lián)系人管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
spring聲明式事務(wù)@Transactional底層工作原理
這篇文章主要為大家介紹分析spring聲明式事務(wù)@Transactional底層工作原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-02-02
spring boot 若依系統(tǒng)整合Ueditor部署時(shí)上傳圖片錯(cuò)誤問(wèn)題
這篇文章主要介紹了spring boot 若依系統(tǒng)整合Ueditor部署時(shí)上傳圖片錯(cuò)誤問(wèn)題,本文給大家分享問(wèn)題解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
關(guān)于Unsupported major.minor version 49.0的錯(cuò)誤解決辦法
這篇文章主要介紹了關(guān)于Unsupported major.minor version 49.0的錯(cuò)誤解決辦法的相關(guān)資料,需要的朋友可以參考下2015-11-11
Spring Boot 項(xiàng)目中使用Swagger2的示例
本篇文章主要介紹了Spring Boot 項(xiàng)目中使用Swagger2的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
基于SpringBoot實(shí)現(xiàn)驗(yàn)證碼功能(兩種驗(yàn)證碼方式)
這篇文章主要介紹了基于SpringBoot實(shí)現(xiàn)驗(yàn)證碼功能,今天我們介紹的是兩種主流的驗(yàn)證碼,一種就是進(jìn)行計(jì)算的驗(yàn)證碼,另外一種就是不需要計(jì)算,直接輸入的驗(yàn)證碼,需要的朋友可以參考下2024-08-08

