Reputation: 53
In the below snippet , I found a sockaddr_in is type converted as sockaddr as '(struct sockaddr *) &sin' . I just want to know what are the variables that are in sockaddr_in will be mapped correspondingly to sockaddr . Below is the snippet.
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
// IPv4 AF_INET sockets:
struct sockaddr_in {
short sin_family; // e.g. AF_INET, AF_INET6
unsigned short sin_port; // e.g. htons(3490)
struct in_addr sin_addr; // see struct in_addr, below
char sin_zero[8]; // zero this if you want to
};
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(floodport);
sin.sin_addr.s_addr = inet_addr(argv[1]);
//type conversion
(struct sockaddr *) &sin // what values of sockaddr_in would be mapped to sockaddr ?
this conversion is used in sendto() in socket programming as below .
sendto(s, datagram, iph->tot_len,0, (struct sockaddr *) &sin,sizeof(sin))
Thanks in advance .
Upvotes: 3
Views: 757
Reputation: 20392
The functions that use struct sockaddr will only read sa_family and do the opposite cast internally (if they understand what's inside sa_family).
Upvotes: 2
Reputation: 91017
The only purpose for struct sockaddr
is to have one type to pass around to functions like sendto()
etc.
In fact, you don't use it for other purposes, there you have other structs such as
struct sockaddr_in
for the legacy IPv4struct sockaddr_in6
for IPv6struct sockaddr_un
for Unix socketsstruct sockaddr_bth
for Bluetoothstruct sockaddr_storage
which is as large as the largest in your
architecture. Can neatly be used for storing addresses whose type you
don't know.Upvotes: 2