2

I want to print the ip address of the client connected to the server socket. I've seen many answers, but all gone wrong with me. Also please provide the right place to put the piece of code you're answering with

Expected result = IP of client is . . . .

1 Answers1

0

You can use the function inet_ntoa() for this:

printf("IP of client: %s\n", inet_ntoa(cli.sin_addr));

Put this somewhere after you have accept()ed the client connection. To use the function inet_ntoa() you have to include the appropriate header file arpa/inet.h. Otherwise, the returned (64-bit) pointer is crippled to a (32-bit) integer, resulting in a segfault.

You should always enable all warnings; this would have shown you, that the function is undeclared.

Finally, this should result in your desired output.

Ctx
  • 18,090
  • 24
  • 36
  • 51