c - Address family of socket is mentioned in structure and socket creation why? -


my doubt on code of lines in socket program. family of address specified in serv_addr.sin_family = af_inet; sockaddr_in structure, why should mention same in socket(af_inet, sock_stream, 0); socket creation. family address in 2 sentence mean?

struct sockaddr_in serv_addr;  listenfd = socket(af_inet, sock_stream, 0);//here   serv_addr.sin_family = af_inet;//and here serv_addr.sin_addr.s_addr = htonl(inaddr_any); 

socket() creates new socket. needs know address family knows kind of addresses allowed work with, whether ipv4, ipv6, ipx, netlink, etc. address family dictates layout , format address values. instance, af_inet allows ipv4 addresses, whereas af_inet6 allows ipv6 addresses (and ipv4 addresses if socket set dual-stack mode on platforms support feature).

every sockaddr_... structure has family field. sockaddr_... structures can passed around various functions, need know type of address receiving input, , can specify type of address returning output.

the sockaddr_in structure specific ipv4 addresses only, sin_addr field specifies ipv4 address 32bit integer in network byte order. same not true of other sockaddr_... structures.

there special sockaddr_storage structure typically used when writing code works multiple addresses families, when calling functions can accept multiple sockaddr_... types.

so important not socket told address family is, important individual addresses specify own types well. typically, these values match each other (except in case of dual-stack sockets).


Popular posts from this blog