csocketstcpinetd

Recovering IP/Port from Socket Descriptor


I'm writing a clone of inetd in which I must run a server that prints the IP and port of the client connecting to it.

As I overwrite STDIN and STDOUT with the socket descriptor, my initial solution to do this was to recover the sockaddr_in structure, which contains the needed information. Doing this with getsockname(), however, is returning an empty structure, with all bits set to 0.

Any idea of what is wrong with my approach? Are there any other approaches I can use to recover the IP/Port?

Thanks


Solution

  • As R.. pointed out, you should use getpeername. Both that function and getsockname take a file descriptor as its first argument, not a stream pointer (FILE *). Use fileno(stdin) to get the file descriptor for standard input (or hard-code it to STDIN_FILENO, as it's constant).

    Also, the last argument to getsockname and getpeername should be a pointer to socklen_t, not a constant, and you should use a sockaddr_in for TCP/IP:

    struct sockaddr_in peeraddr;
    socklen_t peeraddrlen = sizeof(peeraddr);
    getpeername(STDIN_FILENO, &peeraddr, &peeraddrlen);
    

    See a complete example here.