Java 休息 - 如何获取来电者的 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3825084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:32:44  来源:igfitidea点击:

Rest - how get IP address of caller

javaweb-servicesrestjax-rsrestful-authentication

提问by Wanderer

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?

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

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

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

采纳答案by kukudas

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

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

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

如果我没记错的话,request.getRemoteAddr()还是这样。

回答by Michael Banzon

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.

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

回答by rjdkolb

Inject a HttpServletRequestinto your Rest Service as such:

HttpServletRequest注入您的 Rest 服务,如下所示:

import javax.servlet.http.HttpServletRequest;

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

   String ipAddressRequestCameFrom = requestContext.getRemoteAddr();

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

}

回答by Diogo Valim

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); 

   }
}