![](/img/trans.png)
[英]How can I get the IP address from a ServletRequest, not a HTTPServletRequest ?
[英]How to get client Ip Address in Java HttpServletRequest
我正在嘗試開發一個需要獲取客戶端 IP 地址的 Java Web 應用程序 (Servlet)。
以下是我到目前為止的代碼:
String ipAddress = request.getRemoteAddr();
在這種情況下,大部分時間我都會得到“默認網關地址”(147.120.1.5)。 不是我的機器 IP 地址 (174.120.100.17)。
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
在這種情況下,大部分時間我都會得到“默認網關地址”(147.120.1.5)。 不是我的機器 IP 地址 (174.120.100.17)。
InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.getHostAddress());
在這種情況下,我得到了服務器 IP 地址 (147.120.20.1)。
我的 IP 地址在 147.120.100.17。 現在我不知道如何獲得真實的客戶端IP地址。
非常感謝。
試試這個,
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
參考: http : //www.mkyong.com/java/how-to-get-client-ip-address-in-java/
試試這個。 對於所有條件
private static final String[] HEADERS_TO_TRY = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
private String getClientIpAddress(HttpServletRequest request) {
for (String header : HEADERS_TO_TRY) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
如果您正在嘗試獲取開發環境的 IP 地址,那么您可以使用:-
public String processRegistrationForm(HttpServletRequest request)
{
String appUrl = request.getScheme() + "://"+ request.getLocalAddr();
return appUrl;
}
request.getLocalAddr()
將返回請求接收系統的 IP 地址。
希望能幫助到你。
import java.net.UnknownHostException;
/**
* Simple Java program to find IP Address of localhost. This program uses
* InetAddress from java.net package to find IP address.
*
*/
public class IPTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
//Getting IPAddress of localhost - getHostAddress return IP Address
// in textual format
String ipAddress = addr.getHostAddress();
System.out.println("IP address of localhost from Java Program: " + ipAddress);
//Hostname
String hostname = addr.getHostName();
System.out.println("Name of hostname : " + hostname);
}
}
輸出:
IP address of localhost from Java Program: 190.12.209.123
Name of hostname : PCLOND3433
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.