简体   繁体   English

码头8-websockets:如何获取客户端IP地址?

[英]jetty 8 - websockets : how do I get the client IP address?

Simple task. 简单的任务。 I'm using the websockets server implementation by jetty, and I have to get the client IP address, but I don't know how. 我正在通过码头使用websockets服务器实现,我必须获取客户端IP地址,但是我不知道如何。

I think it is same as it always was, grab IP from HTTPServletRequest#getRemoteAddr() like this: 我认为它与往常一样,从HTTPServletRequest#getRemoteAddr()获取IP,如下所示:

public class WSServlet extends WebSocketServlet {

    ...
    ...

    @Override
    public WebSocket doWebSocketConnect(HttpServletRequest req, String str) {
        System.out.println("IP: "+ req.getRemoteAddr());
        ...
    }
}

如果您使用的是org.eclipse.jetty.websocket.api.Session我将寻求:

session.getRemoteAddress().getAddress().getHostAddress();

If you need it for authentification purposes, you can get it like this: 如果出于身份验证目的需要它,则可以这样获得:

This is just an example: 这只是一个例子:

@Override
public boolean canPublish(BayeuxServer server, ServerSession client,
                          ServerChannel channel, ServerMessage messsage) {
  //
  BayeuxContext context=server.getContext();
  System.out.println(context.getRemoteAddress());
  return true;
}

Please keep in mind that getRemoteAddress returns an InetSocketAddress string. 请记住, getRemoteAddress返回一个InetSocketAddress字符串。 So you also have the port, which looks something like this: 因此,您还有端口,看起来像这样:

/79.111.111.22:49372

Without WebServletSocket: 如果没有WebServletSocket:

public static String getClientIp(Session session) {
        String ip = session.getUserProperties().get("javax.websocket.endpoint.remoteAddress").toString();
        int i1 = ip.indexOf("/");
        int i2 = ip.indexOf(":");
        return ip.substring(i1 + 1, i2);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM