socket_remote46.c (893B)
1 /* ISC license. */ 2 3 #include <skalibs/nonposix.h> 4 5 #include <errno.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <string.h> 9 10 #include <skalibs/uint16.h> 11 #include <skalibs/ip46.h> 12 13 #ifdef SKALIBS_IPV6_ENABLED 14 15 int socket_remote46 (int s, ip46 *ip, uint16_t *port) 16 { 17 struct sockaddr_storage sa ; 18 socklen_t dummy = sizeof sa ; 19 if (getpeername(s, (struct sockaddr *)&sa, &dummy) < 0) return -1 ; 20 if (sa.ss_family == AF_INET6) 21 { 22 struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&sa ; 23 memcpy(ip->ip, sa6->sin6_addr.s6_addr, 16) ; 24 *port = uint16_big(sa6->sin6_port) ; 25 ip->is6 = 1 ; 26 } 27 else if (sa.ss_family == AF_INET) 28 { 29 struct sockaddr_in *sa4 = (struct sockaddr_in *)&sa ; 30 memcpy(ip->ip, &sa4->sin_addr.s_addr, 4) ; 31 *port = uint16_big(sa4->sin_port) ; 32 ip->is6 = 0 ; 33 } 34 else return (errno = EAFNOSUPPORT, -1) ; 35 return 0 ; 36 } 37 38 #endif