3

I'm trying to write server application. I want to get client's ip. My problem is with inet_ntop function. I can't get it working properly. Here is my usage :

void client_loop(uint16_t port) {
     int cfd;
     int socket = bind_socket(port, INADDR_ANY);
     char ip[INET_ADDRSTRLEN];
     struct sockaddr client_addr;
     struct sockaddr_in *addr_in;
     socklen_t cli_len;
     while (work) {
        if ((cfd = TEMP_FAILURE_RETRY(accept(socket, &client_addr, &cli_len))) < 0) {
            if (EAGAIN == errno || EWOULDBLOCK == errno)
                continue;
            ERR("accept");
       }
       addr_in=(struct sockaddr_in *)&client_addr;
       inet_ntop(AF_INET, &(addr_in->sin_addr),ip, sizeof(ip)); 
       printf("INET_NTOP: %s\n",ip);
    }
}

First usage of inet_ntop always returns 0.0.0.0 Then it works properly. When im moving inet_ntop to outside function it works properly only for connections from localhost. Thanks.

EDIT:

Fixed. The problem was that cli_len wasn't initialized so accept wasn't filling client_addr.

With this line its working like a boss:

socklen_t cli_len=sizeof(struct sockaddr);
panJapa
  • 113
  • 1
  • 2
  • 6
  • What does the debugger say of the contents of `addr_in` ? – Medinoc Sep 20 '13 at 12:14
  • An address of 0.0.0.0 means that the socket is listening on all addresses. A specific address like 127.0.0.1 would mean that the server is just listening on that address, but not on any other ones. – linux_fanatic Sep 20 '13 at 12:53

1 Answers1

2

i couldn't find the issue, but i see that you have given cli_len as argument, but you have to use sizeof(ip) in place of the 4 th argument (cli_len) of inet_ntop. and also please check for the cli_len also before calling inet_ntop

John
  • 449
  • 5
  • 12