views:

574

answers:

3

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 likely behind a NAT firewall, and in this case we need the public IP address.

NOTE: Although it would preferably be a generic solution, at a minimum I could use one that retrieves the IP address from an EJB2 call on JBoss 4.2.2

A: 

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

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

Ryan Fernandes
Yes. On JBoss 4.2.2 it throws an exception that it is not an RMI method. I assume because JBoss dispatches the message to the EJB implementation on a different thread than where it listens for the RMI response.
Yishai
+1  A: 

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;
}
MicSim
Thanks for the answer. There are no angle brackets in the worker thread name, though. Perhaps this works for EJB 3 only. I'll have to parse it differently, but this got me to the right place, so I'm accepting this answer.
Yishai
Glad I could help.
MicSim
A: 

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 "";
Yishai