getpeername

This commit is contained in:
Nero 2018-11-08 23:23:24 +00:00
commit 03da5ca451
2 changed files with 43 additions and 0 deletions

4
Makefile Normal file
View File

@ -0,0 +1,4 @@
all: getpeername
clean:
rm getpeername

39
getpeername.c Normal file
View File

@ -0,0 +1,39 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char **argv) {
struct sockaddr_storage peer;
socklen_t peersize = sizeof peer;
char hostname[256];
char portname[32];
if (getpeername(0, (struct sockaddr * restrict)&peer, &peersize) < 0) {
perror("getpeername");
exit(1);
}
int v;
v = getnameinfo((struct sockaddr * restrict)&peer,
sizeof(struct sockaddr_storage),
hostname,
sizeof(hostname),
portname,
sizeof(portname),
NI_NUMERICHOST | NI_NUMERICSERV);
if (v < 0) {
printf("getnameinfo: %s\n", gai_strerror(v));
exit(1);
}
printf("%s %s\n", hostname, portname);
return 0;
}