How can a server get the IP address of the caller?

If a server wants to know the IP address of the client that invokes an operation, it can do so by using the Current object. For example, assume that sayHello is an operation on a servant. The Current object that is passed to the operation has a con member of type Connection. In turn, Connection has a getInfo operation that returns an object of type ConnectionInfo. You can downcast this object to a transport-specific type to obtain more information about the connection, as shown in the example below:

C++
void
HelloI::sayHello(const Ice::Current& c)
{
    if(c.con)
    {
        shared_ptr<Ice::ConnectionInfo> info = c.con->getInfo();
        shared_ptr<Ice::TCPConnectionInfo> tcpInfo = dynamic_pointer_cast<Ice::TCPConnectionInfo>(info);
        if(tcpInfo)
        {
            cout << "local address = " << tcpInfo->localAddress << ":" << tcpInfo->localPort << endl;
            cout << "remote address = " << tcpInfo->remoteAddress << ":" << tcpInfo->remotePort << endl;
        }
    }
    // ...
}

Prior to Ice 3.4, the only way to get this information was to call the toString operation on a connection:

C++
void
HelloI::sayHello(const Ice::Current& c)
{
    if(c.con)
    {
        cout << c.con->toString() << endl;
    }
    // ...
}

The local address is the address of the server, and the remote address is the address of the client. The code tests whether c.con is nil in case client and server are collocated in the same address space and use the same communicator; for such a collocated call, the con member of Ice::Current is nil.

Note that, if the client is connected to the server via Glacier2, what is reported as the remote address is the Glacier2 endpoint that forwards the request, not the original endpoint of the client.

Also note that this information is provided mainly for debugging and tracing purposes. In particular, your program should not attach any meaning to the life time of a connection. (For more information, see Why does Ice not provide a callback to notify of connection closure?)

See Also