How can you get the calling ip address on an ejb call?

后端 未结 4 1116
失恋的感觉
失恋的感觉 2020-12-19 22:23

If a java client calls a remote EJB on a different server, how can you get the client IP address? Note that it is important to get it from the server, because the client is

相关标签:
4条回答
  • 2020-12-19 22:28

    Thanks to MicSim, I learned that the thread name stores the IP address. In JBoss 4.2.2 the thread name for EJB2 items look like this:

    http-127.0.0.1-8080-2

    (I assume the http is optional, depending on the protocol actually used).

    This can then be parsed with a regular expression as so:

        Pattern pattern = Pattern.compile("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b");
        Matcher matcher = pattern.matcher(Thread.currentThread().getName());
        if (matcher.find()) {
            return matcher.group();
        }
        return "";
    
    0 讨论(0)
  • 2020-12-19 22:29

    Have you tried: java.rmi.server.RemoteServer.getClientHost() ?

    http://java.sun.com/j2se/1.5.0/docs/api/java/rmi/server/RemoteServer.html#getClientHost()

    0 讨论(0)
  • 2020-12-19 22:35

    I believe that name of the current worker thread contains an IP address of the server, but not the client's IP since threads are pooled rather than created for each call. In JBoss 4, one can use the following workaround to obtain an IP address of the client:

            try {
                //Reflection is used to avoid compile-time dependency on JBoss internal libraries
                Class clazz = Class.forName("org.jboss.web.tomcat.security.HttpServletRequestPolicyContextHandler");
                Field requestContextField = clazz.getDeclaredField("requestContext");
                requestContextField.setAccessible(true);
                ThreadLocal ctx = (ThreadLocal) requestContextField.get(null);
                ServletRequest req = ((ServletRequest) ctx.get());
                return req==null?null:req.getRemoteAddr();
            } catch (Exception e) {
                LOG.log(Level.WARNING, "Failed to determine client IP address",e);
            }
    
    0 讨论(0)
  • 2020-12-19 22:41

    This article on the JBoss community wiki addresses exactly your issue. Prior to JBoss 5 the IP address apparently has to be parsed from the worker thread name. And that seems to be the only way to do it on earlier versions. This is the code snippet doing it (copied from the above link):

    private String getCurrentClientIpAddress() {
        String currentThreadName = Thread.currentThread().getName();
        System.out.println("Threadname: "+currentThreadName);
        int begin = currentThreadName.indexOf('[') +1;
        int end = currentThreadName.indexOf(']')-1;
        String remoteClient = currentThreadName.substring(begin, end);
        return remoteClient;
    }
    
    0 讨论(0)
提交回复
热议问题