chercheur2017
chercheur2017

Reputation: 1

How to get IP address of a web service client?

I created a web service using Eclipse (luna), Tomcat8 and Axis2.To do, I wrote in Java a class 'AddOperator' defining the service as folow:

public class AddOperator {
    public int add(int x,int y) {
        return x+y;
    }
}

I created also a client who consomms this service using the class'AddClientOpp' as folow:

public class AddClientOpp {
    public static void main(String[] args) throws RemoteException  {
        AddOperatorStub stub = new AddOperatorStub();

        Add add = new Add();
        add.setX(25);
        add.setY(30);

        System.out.println(stub.add(add).get_return());
    }
}  

Now, I need to obtain the client's IP adress consomming my web service. I searched and found a few methods and portions of codes that would allow to do this, such as:

import javax.servlet.http.HttpServletRequest;

//...

private static String getClientIp(HttpServletRequest request) {
    String remoteAddr = "";

    if (request != null) {
        remoteAddr = request.getHeader("X-FORWARDED-FOR");
        if (remoteAddr == null || "".equals(remoteAddr)) {
            remoteAddr = request.getRemoteAddr();
        }
    }
    return remoteAddr;
}

or:

import java.net.*;
import java.io.*;
import java.applet.*;

public class GetClientIP extends Applet {
    public void init() {
        try {
           InetAddress Ip =InetAddress.getLocalHost();
           System.out.println("IP:"+Ip.getHostAddress());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

But I do not know where to integrate these code portions or methods into my web service creation process described above!!

if someone has an idea about thi please tell me what i have to do. it's verry important for my project!!

thanks.

Upvotes: 0

Views: 832

Answers (1)

Andreas Veithen
Andreas Veithen

Reputation: 9154

You can use the following code to retrieve the client address:

MessageContext.getCurrentMessageContext().getProperty(MessageContext.REMOTE_ADDR)

Upvotes: 1

Related Questions