xref: /plan9/sys/src/ape/lib/bsd/getpeername.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 /* posix */
2 #include <sys/types.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <errno.h>
9 
10 /* bsd extensions */
11 #include <sys/uio.h>
12 #include <sys/socket.h>
13 #include <netinet/in.h>
14 #include <sys/un.h>
15 
16 #include "priv.h"
17 
18 int
19 getpeername(int fd, struct sockaddr *addr, int *alen)
20 {
21 	Rock *r;
22 	int i;
23 	struct sockaddr_in *rip;
24 	struct sockaddr_un *runix;
25 
26 	r = _sock_findrock(fd, 0);
27 	if(r == 0){
28 		errno = ENOTSOCK;
29 		return -1;
30 	}
31 
32 	switch(r->domain){
33 	case PF_INET:
34 		rip = (struct sockaddr_in*)&r->raddr;
35 		memmove(addr, rip, sizeof(struct sockaddr_in));
36 		*alen = sizeof(struct sockaddr_in);
37 		break;
38 	case PF_UNIX:
39 		runix = (struct sockaddr_un*)&r->raddr;
40 		i = &runix->sun_path[strlen(runix->sun_path)] - (char*)runix;
41 		memmove(addr, runix, i);
42 		*alen = i;
43 		break;
44 	default:
45 		errno = EAFNOSUPPORT;
46 		return -1;
47 	}
48 	return 0;
49 }
50