Reputation: 1089
My doubt is over the code of lines in the socket program. The family of address is specified in serv_addr.sin_family = AF_INET;
sockaddr_in structure, but then why should we mention the same in socket(AF_INET, SOCK_STREAM, 0);
socket creation. What does the family address in two 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);
Upvotes: 0
Views: 488
Reputation: 595792
socket()
creates a new socket. It needs to know what its address family is so it knows what kind of addresses it is allowed to work with, whether that be IPv4, IPv6, IPX, NetLink, etc. The address family dictates the layout and format for its address values. For instance, AF_INET
only allows IPv4 addresses, whereas AF_INET6
allows IPv6 addresses (and IPv4 addresses if the socket is set to dual-stack mode on platforms that support that feature).
Every sockaddr_...
structure has a family field. sockaddr_...
structures can be passed around to various functions, which need to know what type of address they are receiving as input, and can specify what type of address they are returning as output.
The sockaddr_in
structure is specific to IPv4 addresses only, where its sin_addr
field specifies the IPv4 address as a 32bit integer in network byte order. The same is not true of other sockaddr_...
structures.
There is a special sockaddr_storage
structure that is typically used when writing code that works with multiple addresses families, especially when calling functions that can accept multiple sockaddr_...
types.
So it is important not only for the socket to be told what its address family is, but it is also important for individual addresses to specify their own types as well. Typically, these values will match each other (except in the case of dual-stack sockets).
Upvotes: 2