c - getaddrinfo and IPv6 -
i'm trying understand getaddrinfo function returns :
#include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <netdb.h> int main (int argc, char *argv[]) { struct addrinfo *res = 0 ; getaddrinfo("localhost", null ,null,&res); printf("ai_flags -> %i\n", res->ai_flags) ; printf("ai_family -> %i\n", res->ai_family) ; printf("ai_socktype -> %i\n", res->ai_socktype) ; printf("ai_protocol -> %i\n", res->ai_protocol) ; printf("ai_addrlen -> %i\n", res->ai_addrlen) ; struct sockaddr_in* saddr = (struct sockaddr_in*)res->ai_addr; printf("ai_addr hostname -> %s\n", inet_ntoa(saddr->sin_addr)); freeaddrinfo(res); return 0 ; }
results :
ai_flags -> 40 ai_family -> 2 ai_socktype -> 1 ai_protocol -> 6 ai_addrlen -> 16 ai_addr hostname -> 127.0.0.1
in /etc/hosts, 've got :
127.0.0.1 localhost ::1 localhost
getaddrinfo returns 127.0.0.1 , not ::1 ? don't understand why ?
the second question can find meaning of ints (40,2,1,6 etc) ? i've read man there nothing that.
i wanted know if it's possible give ipv6 adress (for example ::1) , function returns name : localhost ?
thanks lot !!
@jwodder , @onteria_ covered ipv6 portion well, i'll tackle numbers portion:
ai_flags -> 40
probably going sum of following 2 in /usr/include/netdb.h
:
# define ai_v4mapped 0x0008 /* ipv4 mapped addresses acceptable. */ # define ai_addrconfig 0x0020 /* use configuration of host choose
this protocol family, inet, inet6, apx, unix, etc.:
ai_family -> 2 bits/socket.h:78:#define pf_inet 2 /* ip protocol family. */ bits/socket.h:119:#define af_inet pf_inet
this socket type, stream, dgram, packet, rdm, seqpacket:
ai_socktype -> 1 bits/socket.h:42: sock_stream = 1, /* sequenced, reliable, connection-based
the higher-level protocol, tcp, udp, tcp6, udp6, udplite, ospf, icmp, etc:
ai_protocol -> 6
funny enough, in /etc/protocols
:
tcp 6 tcp # transmission control protocol
the size of struct sockaddr
. (differs based on address family! ugh.)
ai_addrlen -> 16
this because you're getting struct sockaddr_in
, see linux/in.h
:
#define __sock_size__ 16 /* sizeof(struct sockaddr) */ struct sockaddr_in { sa_family_t sin_family; /* address family */ __be16 sin_port; /* port number */ struct in_addr sin_addr; /* internet address */ /* pad size of `struct sockaddr'. */ unsigned char __pad[__sock_size__ - sizeof(short int) - sizeof(unsigned short int) - sizeof(struct in_addr)]; };
and last one, /etc/hosts
:)
ai_addr hostname -> 127.0.0.1
Comments
Post a Comment