[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [Libevent-users] How do I get the client IP address?





On Fri, Dec 10, 2010 at 5:10 AM, Christian Dahlqvist <acdahlqvist@xxxxxxxxx> wrote:
I am unfortunately not doing HTTP, so that approach will not work for me.

I am building my code on a bufferevent sample for a custom protocol,
and I guess I could try to get it based on the raw socket, but am
reluctant to do so since it would possibly make it more difficult to
port later on. The portability aspect is one of the reasons I started
with libevent in the first place.

Christian

You need to use the socket API during you accept() callback.

struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);

if (ss.ss_family == AF_INET)
{
inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
}
else if (ss.ss_family == AF_INET6)
{
    inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
}
else
{
// Handle other protocols or boot the client
}
evutil_inet_ntop(ss.ss_family, inaddr, player->ip, sizeof(player->ip));

In the above case, replace player->ip with the storage location of your choice (a char[128] array).

Regards,
Kevin