0

I have this code in server program

if ((new_socket = accept(server_fd, (struct sockaddr *)&client_ip,
        (socklen_t*)&addrlen))<0)
        {
            perror("accept");
            exit(EXIT_FAILURE);
        }

I like to know does second argument to accept(...) (which is of type struct sockaddr * ) get filled with the ip address of client that connects to my server.

For example I like to print the ip address so if I have

  struct sockaddr client_ip;

after passing address of above struct sockaddr how to print ip address of client machine. I dont know how to do it the right way

On this link Getting IPV4 address from a sockaddr structure

it shows like this

  char *ip = inet_ntoa(client_ip.sin_addr);

I like to know if above char *ip is null terminated or not.

F.Hoque
  • 8,304
  • 5
  • 9
  • 28
user786
  • 3,502
  • 3
  • 28
  • 56
  • 2
    Yes, `inet_ntoa()` returns a null-terminated string. As for `client_ip`, declaring it as `sockaddr` is wrong. It needs to be declared as `sockaddr_in`, `sockaddr_in6`, or `sockaddr_storage`, depending on whether `server_fd` is an IPv4, IPv6, or dual-stack socket, respectively. However, `inet_ntoa()` works only for IPv4 addresses. Use `inet_ntop()` instead if you need to handle IPv6 or dual-stack sockets – Remy Lebeau Oct 09 '21 at 22:27

0 Answers0