getpeername
Program to determine ip-address of connected peer on file descriptor 0.
// vi:set nu ai ap smd showmatch tabstop=4 shiftwidth=4:
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <syslog.h>
// this program will return the ip-address of the socket connected on
// file descriptor 0. I use this when creating a Inetd service, using
// script. Inetd will listen on the defined port, fork a child (the
// script), and pass the socket onto file descriptor 0 when executing
// the child.
// This is a neat way to create a network service out of a script.
// also, the script will log to syslog, if a failure on getting the
// peername of the connected socket occurs.
int main(int argc, char **argv) {
int addrlen;
struct sockaddr_in his_addr;
addrlen = sizeof(his_addr);
if (getpeername(0, (struct sockaddr *) &his_addr, &addrlen) < 0) {
syslog(LOG_ERR, "getpeername (%s): %m", argv[0]);
exit(1);
}
printf("%s\n", inet_ntoa(his_addr.sin_addr));
exit(0);
}