UNIX sendto() without destination port - c

I'm new to unix socket programming. I have some questions about unix sendto() function.
ssize_t sendto(int sockfd,
const void *buf,
size_t len,
int flags,
const struct sockaddr *dest_addr,
socklen_t addrlen);
My questions are:
(1) If port number in dest_addr is not set, how would the receiver host deal with the packet?
(2) How does this functions process info in dest_addr? I send IPv6 packet with this function, I have to use sockaddr_in6 struct which is a totally different with sockaddr_in struct:
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_in6 {
u_int16_t sin6_family; // address family, AF_INET6
u_int16_t sin6_port; // port number, Network Byte Order
u_int32_t sin6_flowinfo; // IPv6 flow information
struct in6_addr sin6_addr; // IPv6 address
u_int32_t sin6_scope_id; // Scope ID
};
and why do we need a cast to struct sockaddr in sendto()? Looks like only sa_family is meaningful to this function. Then what about other fields?

Regarding 1: there is no special "undefined" value. Whatever value happens to be stored in this memory location will be taken as the desired port number.
Regarding 2: each struct sockaddr starts with an address family identifier. If the family is set to AF_INET, all functions will know to expect a struct sockaddr_in. Likewise for the other families. In that sense, I believe the example you posted (which seems to imply AF_INET6 can be a valid value of sin_family in a struct sockaddr_in) to be misleading.

Related

What is the purpose of the sa_data field in a sockaddr?

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
The actual structure passed for the addr argument will depend on the address family. The sockaddr structure is defined as something like:
struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
}
So for an IPv4 address (AF_INET), the actual struct that will be passed is this:
/* Source http://linux.die.net/man/7/ip */
struct sockaddr_in {
sa_family_t sin_family; /* address family: AF_INET */
in_port_t sin_port; /* port in network byte order */
struct in_addr sin_addr; /* internet address */
};
/* Internet address. */
struct in_addr {
uint32_t s_addr; /* address in network byte order */
};
Does the bind code read the sockaddr.sa_family value and depending on the value it finds, it will then cast the sockaddr struct into the appropriate struct such as sockaddr_in?
Why is the sa_data set to 14 characters? If I understand correct, the sa_data field is just a field that will have large enough memory space to fit all address family types? Presumably the original designers anticipated that 14 characters would be wide enough to fit all future types.
According to the glibc manual:
The length 14 of sa_data is essentially arbitrary.
And the FreeBSD developers handbook mentions the following:
Please note the vagueness with which the sa_data field is declared,
just as an array of 14 bytes, with the comment hinting there can be
more than 14 of them.
This vagueness is quite deliberate. Sockets is a very powerful
interface. While most people perhaps think of it as nothing more than
the Internet interface—and most applications probably use it for that
nowadays—sockets can be used for just about any kind of interprocess
communications, of which the Internet (or, more precisely, IP) is only
one.
Yes, the sa_family field is used to recognize how to treat the struct passed (which is cast to struct sockaddr* in a call to bind). You can read more about how it works also in a FreeBSD developers handbook.
And actually there are "polymorphic" (sub)types of sockaddr, in which sa_data contains more than 16 bytes, for example:
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* pathname */
};
The sockaddr struct is used as a tagged union. By reading the sa_family field it can be cast to a struct of the proper form.
The 14 bytes is arbitrary. It's big enough to hold IPv4 addresses, but not big enough to hold IPv6 addresses. There is also a sockaddr_storage struct which is big enough for both. Reading the Microsoft docs on SOCKADDR_STORAGE, it comes in at 128 bytes, so much larger than needed for IPv6. Checking some Linux headers, it seems to be at least that large there as well.
For reference, the IPv6 struct is:
struct sockaddr_in6 {
u_int16_t sin6_family; // address family, AF_INET6
u_int16_t sin6_port; // port number, Network Byte Order
u_int32_t sin6_flowinfo; // IPv6 flow information
struct in6_addr sin6_addr; // IPv6 address
u_int32_t sin6_scope_id; // Scope ID
};
struct in6_addr {
unsigned char s6_addr[16]; // IPv6 address
};
As you can see, the 16 byte s6_addr field is already bigger than the 14 byte sa_data field on it's own. Total size after the sa_family field is 26 bytes.

Why do we cast sockaddr_in to sockaddr when calling bind()?

The bind() function accepts a pointer to a sockaddr, but in all examples I've seen, a sockaddr_in structure is used instead, and is cast to sockaddr:
struct sockaddr_in name;
...
if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
...
I can't wrap my head around why is a sockaddr_in struct used. Why not just prepare and pass a sockaddr?
Is it just convention?
No, it's not just convention.
sockaddr is a generic descriptor for any kind of socket operation, whereas sockaddr_in is a struct specific to IP-based communication (IIRC, "in" stands for "InterNet"). As far as I know, this is a kind of "polymorphism" : the bind() function pretends to take a struct sockaddr *, but in fact, it will assume that the appropriate type of structure is passed in; i. e. one that corresponds to the type of socket you give it as the first argument.
I don't know if its very much relevant for this question, but I would like to provide some extra info which may make the typecaste more understandable as many people who haven't spent much time with C get confused seeing such a typecaste.
I use macOS, so I am taking examples based on header files from my system.
struct sockaddr is defined as follows:
struct sockaddr {
__uint8_t sa_len; /* total length */
sa_family_t sa_family; /* [XSI] address family */
char sa_data[14]; /* [XSI] addr value (actually larger) */
};
struct sockaddr_in is defined as follows:
struct sockaddr_in {
__uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
Starting from the very basics, a pointer just contains an address. So struct sockaddr * and struct sockaddr_in * are pretty much the same. They both just store an address. Only relevant difference is how compiler treats their objects.
So when you say (struct sockaddr *) &name, you are just tricking the compiler and telling it that this address points to a struct sockaddr type.
So let's say the pointer is pointing to a location 1000. If the struct sockaddr * stores this address, it will consider memory from 1000 to sizeof(struct sockaddr) possessing the members as per the structure definition. If struct sockaddr_in * stores the same address it will consider memory from 1000 to sizeof(struct sockaddr_in).
When you typecasted that pointer, it will consider the same sequence of bytes upto sizeof(struct sockaddr).
struct sockaddr *a = &name; // consider &name = 1000
Now if I access a->sa_len, the compiler would access from location 1000 to sizeof(__uint8_t) which is same bytes size as in case of sockaddr_in. So this should access the same sequence of bytes.
Same pattern is for sa_family.
After that there is a 14 byte character array in struct sockaddr which stores data from in_port_t sin_port (typedef'd 16 bit unsigned integer = 2 bytes ) , struct in_addr sin_addr (simply a 32 bit ipv4 address = 4 bytes) and char sin_zero[8](8 bytes). These 3 add up to make 14 bytes.
Now these three are stored in this 14 bytes character array and we can access any of these three by accessing appropriate indices and typecasting them again.
user529758's answer already explains the reason to do this.
This is because bind can bind other types of sockets than IP sockets, for instance Unix domain sockets, which have sockaddr_un as their type. The address for an AF_INET socket has the host and port as their address, whereas an AF_UNIX socket has a filesystem path.

Reasoning behind C sockets sockaddr and sockaddr_storage

I'm looking at functions such as connect() and bind() in C sockets and notice that they take a pointer to a sockaddr struct. I've been reading and to make your application AF-Independent, it is useful to use the sockaddr_storage struct pointer and cast it to a sockaddr pointer because of all the extra space it has for larger addresses.
What I am wondering is how functions like connect() and bind() that ask for a sockaddr pointer go about accessing the data from a pointer that points at a larger structure than the one it is expecting. Sure, you pass it the size of the structure you are providing it, but what is the actual syntax that the functions use to get the IP Address off the pointers to larger structures that you have cast to struct *sockaddr?
It's probably because I come from OOP languages, but it seems like kind of a hack and a bit messy.
Functions that expect a pointer to struct sockaddr probably typecast the pointer you send them to sockaddr when you send them a pointer to struct sockaddr_storage. In that way, they access it as if it was a struct sockaddr.
struct sockaddr_storage is designed to fit in both a struct sockaddr_in and struct sockaddr_in6
You don't create your own struct sockaddr, you usually create a struct sockaddr_in or a struct sockaddr_in6 depending on what IP version you're using. In order to avoid trying to know what IP version you will be using, you can use a struct sockaddr_storage which can hold either. This will in turn be typecasted to struct sockaddr by the connect(), bind(), etc functions and accessed that way.
You can see all of these structs below (the padding is implementation specific, for alignment purposes):
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
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_in6 {
u_int16_t sin6_family; // address family, AF_INET6
u_int16_t sin6_port; // port number, Network Byte Order
u_int32_t sin6_flowinfo; // IPv6 flow information
struct in6_addr sin6_addr; // IPv6 address
u_int32_t sin6_scope_id; // Scope ID
};
struct sockaddr_storage {
sa_family_t ss_family; // address family
// all this is padding, implementation specific, ignore it:
char __ss_pad1[_SS_PAD1SIZE];
int64_t __ss_align;
char __ss_pad2[_SS_PAD2SIZE];
};
So as you can see, if the function expects an IPv4 address, it will just read the first 4 bytes (because it assumes the struct is of type struct sockaddr. Otherwise it will read the full 16 bytes for IPv6).
In C++ classes with at least one virtual function are given a TAG. That tag allows you to dynamic_cast<>() to any of the classes your class derives from and vice versa. The TAG is what allows dynamic_cast<>() to work. More or less, this can be a number or a string...
In C we are limited to structures. However, structures can also be assigned a TAG. In fact, if you look at all the structures that theprole posted in his answer, you will notice that they all start with 2 bytes (an unsigned short) which represents what we call the family of the address. This defines exactly what the structure is and thus its size, fields, etc.
Therefore you can do something like this:
int bind(int fd, struct sockaddr *in, socklen_t len)
{
switch(in->sa_family)
{
case AF_INET:
if(len < sizeof(struct sockaddr_in))
{
errno = EINVAL; // wrong size
return -1;
}
{
struct sockaddr_in *p = (struct sockaddr_in *) in;
...
}
break;
case AF_INET6:
if(len < sizeof(struct sockaddr_in6))
{
errno = EINVAL; // wrong size
return -1;
}
{
struct sockaddr_in6 *p = (struct sockaddr_in6 *) in;
...
}
break;
[...other cases...]
default:
errno = EINVAL; // family not supported
return -1;
}
}
As you can see, the function can check the len parameter to make sure that the length is enough to fit the expected structure and therefore they can reinterpret_cast<>() (as it would be called in C++) your pointer. Whether the data is correct in the structure is up to the caller. There is not much choice on that end. These functions are expected to verify all sorts of things before it uses the data and return -1 and errno whenever a problem is found.
So in effect, you have a struct sockaddr_in or struct sockaddr_in6 that you (reinterpret) cast to a struct sockaddr and the bind() function (and others) cast that pointer back to a struct sockaddr_in or struct sockaddr_in6 after they checked the sa_family member and verified the size.

struct type conversion in C

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 .
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 IPv4
struct sockaddr_in6 for IPv6
struct sockaddr_un for Unix sockets
struct sockaddr_bth for Bluetooth
struct 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.
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).

What does the abbreviation "s_", "ai_", "sin_", "in" (if such) in the IP structures mean?

Pretty simple questions. And yes, maybe not (that) important, but I'm really curious what do they mean and I couldn't find their meanings.
// ipv4
struct sockaddr_in {
short int sin_family; // Address family, AF_INET
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr
};
// ipv4
struct in_addr {
uint32_t s_addr; // that's a 32-bit int (4 bytes)
};
// ipv6
struct addrinfo {
int ai_flags; // AI_PASSIVE, AI_CANONNAME, etc.
int ai_family; // AF_INET, AF_INET6, AF_UNSPEC
int ai_socktype; // SOCK_STREAM, SOCK_DGRAM
int ai_protocol; // use 0 for "any"
size_t ai_addrlen; // size of ai_addr in bytes
struct sockaddr *ai_addr; // struct sockaddr_in or _in6
char *ai_canonname; // full canonical hostname
struct addrinfo *ai_next; // linked list, next node
};
// ipv6
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
sin_ means sockaddr_in, ai_ means addrinfo, sa_ means sockaddr. I'm not sure about the s_ in in_addr. The sockets API was designed with pre-standard early 1980s C compilers in mind, which might have had a single namespace for all struct members.
larsman is mostly right, but it's not merely a matter of legacy single-namespace considerations. All the structs defined in standard headers use names of this form to avoid stepping on the application's namespace for macros. If struct members were not prefixed with ai_, sin_, etc., then whatever member names were included in the struct (including extensions not even specified in the C or POSIX standards) would clash and result in errors if an application defined the same name as a preprocessor macro. By using these "struct-local namespaces" that can be reserved by simple pattern rules in the standards (for instance, netdb.h reserves ai_*) there is a clear distinction between names reserved for use by the implementation and names reserved for use by the application, and new extensions or new revisions of the standard will not result in clashes.
The Microsoft definition of in_addr could imply that the "S_" prefix means struct as per #R..'s answer and seeing "un" for union, however they use a capital "S" unlike POSIX land.
typedef struct in_addr {
union {
struct {
u_char s_b1,s_b2,s_b3,s_b4;
} S_un_b;
struct {
u_short s_w1,s_w2;
} S_un_w;
u_long S_addr;
} S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
For the set of socket structures "s" usually means "sock" short for "socket", so there does not appear to be a definition reason.
For curiosity the MSDN page on IPv6 Support shows struct in6_addr containing the name s6_addr implying the IPv6 version of an IPv4 "socket" structure rather than just a "IPv4 structure".

Resources