0

I implement echo server given in the libevent book.

I modify accept_conn_cb function so that the server prints the IPv4 address of a newly created connection (in decimal dot notation). The following is my callback

static void accept_conn_cb(
  struct evconnlistener *listener,
  evutil_socket_t fd, 
  struct sockaddr *address, 
  int socklen,
  void *ctx)
{
   char ipAddress[INET_ADDRSTRLEN];

   struct sockaddr_in * saddr_in = (struct sockaddr_in *) &address;

   if (!inet_ntop(AF_INET, &(saddr_in->sin_addr), ipAddress, INET_ADDRSTRLEN))
      puts("Couldn't retrieve IPv4 address");

   printf("A new connection established from %s\n", ipAddress);

   /* ... */

When I compile and run it it always prints the follwoing strange addresses:

A new connection established from 252.127.0.0 or

A new connection established from 253.127.0.0 or

A new connection established from 255.127.0.0

no matter from what machine I connect. I use telnet for testing connections.

I have written another version of an echo server written in pure C (without libevent).When I run it it always returns the right address.

fade2black
  • 546
  • 1
  • 10
  • 26
  • I have successfully retrieved the remote address using `getpeername`, but still wonder why `inet_ntop` does not work. It seems something wrong with `address ` parameter of the callback. – fade2black Jun 10 '16 at 23:48
  • 1
    You are passing in "address" as a pointer to a sockaddr structure (although it is probably a pointer to a sockaddr_in). Then you are "casting" it as a pointer to a sockaddr_in... (i.e. saddr_in)... BUT you are taking the ADDRESS of it instead of "address" itself... Instead of saddr_in = (struct sockaddr_in *) &address; You should be doing saddr_in = (struct sockaddr_in *) address; (Note NO ampersand). – TonyB Jun 11 '16 at 20:39
  • @TonyB you are right. Worked. – fade2black Jun 12 '16 at 18:04

0 Answers0