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);
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