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
As R.. pointed out, you should use
getpeername. Both that function andgetsocknametake a file descriptor as its first argument, not a stream pointer (FILE *). Usefileno(stdin)to get the file descriptor for standard input (or hard-code it toSTDIN_FILENO, as it's constant).Also, the last argument to
getsocknameandgetpeernameshould be a pointer tosocklen_t, not a constant, and you should use asockaddr_infor TCP/IP:See a complete example here.