Rest - 如何获取呼叫者的IP地址

发布于 2024-09-25 14:48:31 字数 141 浏览 7 评论 0原文

我正在编写 Java Rest Web 服务,需要调用者的 IP 地址。我以为我曾经在饼干中看到过这个,但现在我看不到了。有一致的地方可以获取这些信息吗?

我看到一个使用“OperationalContext”来获取它的示例,但这不是在 java 中。

I am writing a Java Rest Web Service and need the caller's IP Address. I thought I saw this in the cookie once but now I don't see it. Is there a consistent place to get this information?

I saw one example of using an "OperationalContext" to get it but that was not in java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

甜中书 2024-10-02 14:48:31

HttpServletRequest 注入到您的 Rest 服务中例如:

import javax.servlet.http.HttpServletRequest;

@GET
@Path("/yourservice")
@Produces("text/xml")
public String activate(@Context HttpServletRequest req,@Context SecurityContext context){

   String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
   // header name is case insensitive
   String xForwardedForIP = req.getHeader("X-Forwarded-For");

   // if xForwardedForIP is populated use it, else return ipAddressRequestCameFrom 
   String ip = xForwardedForIP != null ? xForwardedForIP : ipAddressRequestCameFrom;
   System.out.println("IP is "+ip);


   // get the host name the client contacted. If the header `Host` is populated the `Host` header is automatically returned.
   // An AWS ALB populated the Host header for you.
   String hostNameRequestCameFrom = req.getServerName();
   System.out.println("Host is "+hostNameRequestCameFrom);

   
   //Also if security is enabled
   Principal principal = context.getUserPrincipal();
   String userName = principal.getName();

}

正如 @Hemant Nagpal 提到的,您还可以检查 X-Forwarded-For 标头以确定负载均衡器是否插入此标头进入请求。
根据这个答案getHeader() 调用不区分大小写。

您还可以获取客户端联系的服务器名称。这是 DNS 名称或 Host< 中设置的值可以填充带有 OSI 第 7 层负载均衡器的 /a> 标头。

1.示例:未填充任何标头

curl "http://127.0.0.1:8080/"

返回

IP is 127.0.0.1
Host is 127.0.0.1

2。示例:填充 X-Forwarded-For 和 Host 标头

curl --header "X-Forwarded-For: 1.2.3.4" --header "Host: bla.bla.com:8443" "http://127.0.0.1:8080/"

返回

IP is 1.2.3.4
Host is bla.bla.com

Inject a HttpServletRequest into your Rest Service as such:

import javax.servlet.http.HttpServletRequest;

@GET
@Path("/yourservice")
@Produces("text/xml")
public String activate(@Context HttpServletRequest req,@Context SecurityContext context){

   String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
   // header name is case insensitive
   String xForwardedForIP = req.getHeader("X-Forwarded-For");

   // if xForwardedForIP is populated use it, else return ipAddressRequestCameFrom 
   String ip = xForwardedForIP != null ? xForwardedForIP : ipAddressRequestCameFrom;
   System.out.println("IP is "+ip);


   // get the host name the client contacted. If the header `Host` is populated the `Host` header is automatically returned.
   // An AWS ALB populated the Host header for you.
   String hostNameRequestCameFrom = req.getServerName();
   System.out.println("Host is "+hostNameRequestCameFrom);

   
   //Also if security is enabled
   Principal principal = context.getUserPrincipal();
   String userName = principal.getName();

}

As @Hemant Nagpal mentions, you can also check the X-Forwarded-For header to determine the real source if a load balancer inserts this into the request.
According to this answer, the getHeader() call is case insensitive.

You can also get the servername that the client contacted. This is either the DNS name or the value set in the Host header with an OSI layer 7 load balancer can populate.

1. Example: no headers are populated

curl "http://127.0.0.1:8080/"

returns

IP is 127.0.0.1
Host is 127.0.0.1

2. Example: X-Forwarded-For and Host headers are populated

curl --header "X-Forwarded-For: 1.2.3.4" --header "Host: bla.bla.com:8443" "http://127.0.0.1:8080/"

returns

IP is 1.2.3.4
Host is bla.bla.com
握住我的手 2024-10-02 14:48:31

我认为你可以通过请求对象获取IP。

如果我没记错的话,request.getRemoteAddr() 左右。

I think you can get the IP through the request object.

If I'm not mistaken, request.getRemoteAddr() or so.

顾铮苏瑾 2024-10-02 14:48:31

你可以这样做:

@WebService
public class YourService {

   @Resource
   WebServiceContext webServiceContext; 

   @WebMethod 
   public String myMethod() { 

      MessageContext messageContext = webServiceContext.getMessageContext();
      HttpServletRequest request = (HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST); 
      String callerIpAddress = request.getRemoteAddr();

      System.out.println("Caller IP = " + callerIpAddress); 

   }
}

You could do something like this:

@WebService
public class YourService {

   @Resource
   WebServiceContext webServiceContext; 

   @WebMethod 
   public String myMethod() { 

      MessageContext messageContext = webServiceContext.getMessageContext();
      HttpServletRequest request = (HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST); 
      String callerIpAddress = request.getRemoteAddr();

      System.out.println("Caller IP = " + callerIpAddress); 

   }
}
臻嫒无言 2024-10-02 14:48:31

假设您正在使用 servlet 来创建“Web 服务”,那么在请求对象上调用 .getRemoteAddr() 的相当简单的方法将为您提供调用者的 IP 地址。

Assuming you are making your "web service" with servlets, the rather simple method call .getRemoteAddr() on the request object will give you the callers IP address.

任性一次 2024-10-02 14:48:31

如果您的应用程序运行在位于反向代理或负载均衡器后面的网络服务器上,则可以配置该代理以将请求的 IP 地址注入请求标头中。不同的反向代理可以注入不同的标头。请参阅代理服务器的文档。我们在下面的示例中列出了一些最常用的,但这绝不是完整的列表。
当您的客户端使用(转发)代理时,它可能会插入标头来说明客户端 IP 地址是什么。或者也可能不会。并且此处插入的 IP 地址可能不正确。
这意味着您通过调用 request.getRemoteAddr() 获得的值是请求的直接上游源的 IP 地址。
正如我们所说,使用的不同代理有许多标头,但 x-forwareded-for 最有可能由代理插入。
最后要注意的是,即使您从标头或 request.getRemoteAddr() 获取 IP 地址,也不能保证它是客户端 IP 地址。例如:如果您的代理不包含客户端的 IP 地址,那么您将获得代理或负载均衡器的 IP 地址。如果您的客户端工作在专用网络上并通过 NAT 网关连接到 Internet,则 HTTP 请求中的 IP 地址将是 NAT 服务器的地址。或者甚至对于黑客来说,注入具有不同 IP 地址的标头也很容易。因此,这意味着您无法可靠地找到发出请求的系统的 IP 地址。

 private static final String[] IP_HEADER_CANDIDATES = { 
        "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" };

    public static String getClientIpAddress(HttpServletRequest request) {
        for (String header : IP_HEADER_CANDIDATES) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

If your application is running on a webserver that is located behind a reverse proxy or load balancer, then that proxy can be configured to inject the requested IP address in a request header. Different reverse proxies can inject different headers. Consult the documentation for your proxy server. We listed a couple of the most used in our example below but this is by no means a complete list.
When your client uses a (forward) proxy, then it might insert headers to say what the client IP addres is. Or it might not. And the IP address inserded here might be incorrect.
This means that the value you get by calling request.getRemoteAddr() is the IP address of the immediate upstream source of the request.
As we said, there are many headers for different proxies in use, but x-forwareded-for is most likely to be inserted by a proxy.
As a last note, even if you get an IP address either from the header or from request.getRemoteAddr() it is not guarenteed to be the client IP address. e.g.: if your proxy does not include the IP address of the client then you’ll get the IP address of the proxy or load balancer. If your client works on a private network and connect to the internet via a NAT gateway, then the IP address in the HTTP request will be an address of the NAT server. Or even for a hacker it is quite easy to inject a header with a different IP address. So this means that you cannot reliably find out the IP address of the system that the request originated from.

 private static final String[] IP_HEADER_CANDIDATES = { 
        "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" };

    public static String getClientIpAddress(HttpServletRequest request) {
        for (String header : IP_HEADER_CANDIDATES) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文