How sockaddr holds sockaddr_storage or sockaddr_in6? - c

I am reading Beej's guide, and he talks about the different structers programmers created.
He says we can pass sockaddr_storage/in6/in to addrinfo, and it will be converted to sockaddr,
but how exactly is it possible? sockaddr is 16 bytes, while sockaddr_in6 is 28 bytes.
I read a little part of RFC 3493:
Notice that the sockaddr_in6 structure will normally be larger than
the generic sockaddr structure. On many existing implementations the
sizeof(struct sockaddr_in) equals sizeof(struct sockaddr), with both
being 16 bytes. Any existing code that makes this assumption needs
to be examined carefully when converting to IPv6.
But it doesn't explain what happens when sockaddr_in6 is casted to sockaddr.

Remember that all functions that take a struct sockaddr pointer, also takes the size of the structure. Together with the meta-data on the actual socket, it's easy for the system to know what kind of structure you're passing.
Also note that it's always pointers to the address structures being passed around, not actual structures which would not work. So you never to e.g.
(struct sockaddr) a_in6_sockaddr
you do
(struct sockaddr *) &a_in6_sockaddr

Related

How do I get sin6_addr from an addrinfo?

My addrinfo pointer looks like this-
struct addrinfo hint, *res = NULL;
I then call get addrinfo.
hint.ai_family = AF_UNSPEC;
ret = getaddrinfo(curhost, NULL, &hint, &res);
curhost is a character array. Doing
saddrv6.sin6_addr=*(res->ai_addr).sin6_addr
is giving me an error that says
request for member 'sin6_addr' in something not a structure or union. saddrv6 is a sockaddr_in6 struct. What is a good way to fill sin6_addr from info that I already have in res? New to C programming here .
The specific error you're getting is because in:
*(res->ai_addr).sin6_addr
The . operator binds more tightly than *. You could change it to:
(*res->ai_addr).sin6_addr
which is probably what you meant, but the better way is to use the -> operator:
res->ai_addr->sin6_addr
However, that still doesn't work because ai_addr has the useless opaque type struct sockaddr *, not struct sockaddr_in6 *. To fix this you need to cast it to a pointer to the type it actually points to:
((struct sockaddr_in6 *)res->ai_addr)->sin6_addr
At this point your code should work. However, ultimately the ai_addr member of struct addrinfo is not really meant to be accessed directly but rather used abstractly and just passed to functions like connect, bind, sendto, recvfrom, etc. At this point we're talking about a matter of style and good programming practices rather than correctness per the language, though.
Note that if you just want to get the IPv6 address for the sake of printing it as a string, the getnameinfo function with the NI_NUMERICHOST flag lets you do this in an abstract way without having to poke through the opaque struct sockaddr *.

Why socklent_t * is used in accept() in socket programming?

In C socket programming the accept() declaration looks like:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
I can understand the uses of sockfd, struct sockaddr *addr.
But why we have to pass the address of the length of the socket, it could have been socklen_t. Because if the accept() function needs the length then it can get it by socklen_t. Why the protype of the function is declared in such that way?
So what is the reason behind using socklen_t * type?
In code that's agnostic to the address/protocol family of the socket it's accepting from, it may be using a generic sockaddr_storage structure to hold the result. The initial value of the pointed-to socklen_t is the size of this storage; the value after accept returns is the actual size of the resulting peer address. Also, some address/protocol families like AF_UNIX have variable length addresses, so even if you know the type you may not know the size.
why addrlen is needed
accept designed to deal with lots of protocal family, their addr struct maybe different length.
The argument addr is a pointer to a sockaddr structure. This structure is filled in with
the address of the peer socket, as known to the communications layer. The exact format
of the address returned addr is determined by the socket's address family (see socket(2)
and the respective protocol man pages). When addr is NULL, nothing is filled in; in this
case, addrlen is not used, and should also be NULL.
why pointer
The addrlen argument is a value-result argument: the caller must initialize it to contain
the size (in bytes) of the structure pointed to by addr; on return it will contain the
actual size of the peer address.
why socklen_t
The socklen_t type
The third argument of accept() was originally declared as an int * (and is that under
libc4 and libc5 and on many other systems like 4.x BSD, SunOS 4, SGI); a POSIX.1g draft
standard wanted to change it into a size_t *, and that is what it is for SunOS 5. Later
POSIX drafts have socklen_t *, and so do the Single UNIX Specification and glibc2. Quot‐
ing Linus Torvalds:
"Any sane library must have "socklen_t" be the same size as int. Anything else
breaks any BSD socket layer stuff. POSIX initially did make it a size_t, and I (and
hopefully others, but obviously not too many) complained to them very loudly indeed.
Making it a size_t is completely broken, exactly because size_t very seldom is the same
size as "int" on 64-bit architectures, for example. And it has to be the same size as
"int" because that's what the BSD socket interface is. Anyway, the POSIX people eventu‐
ally got a clue, and created "socklen_t". They shouldn't have touched it in the first
place, but once they did they felt it had to have a named type for some unfathomable rea‐
son (probably somebody didn't like losing face over having done the original stupid
thing, so they silently just renamed their blunder)."
ref: man accept, man socket

Whats the addrlen field in recvfrom() used for?

I'm using recvfrom in my program to get DGRAM data from a server I specify in src_addr. However, I'm not sure why I need to initialize and pass in addrlen.
I read the man page and I didn't really understand what it's getting at.
If src_addr is not NULL, and the underlying protocol provides the source address, this source address is filled in. When
src_addr is NULL, nothing is filled in; in this case, addrlen is not
used, and should also be NULL. The argument addrlen is a value-result argument, which the caller should initialize before the
call to the size of the buffer associated with src_addr, and
modified on return to indicate the actual size of the source address. The returned address is truncated if the buffer provided is too small;
in this case, addrlen will return a value greater than was supplied to the call.
I'm guessing that it's got something to do with src_addr being ipv4 or ipv6. Is this correct?
Thanks!
Maybe there is a missinterpretation from your side. Talking about:
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
src_addr is not used to hand in the adress that you would like to listen to, but rather a storage location provided by you to get the actual source address handed out.
Thus if you set src_addr to NULL because youre not interested in the address at all, you don't have to care about addrlen as it won't get used anyway.
If on the other hand you want to be informed about the source address, you not only have to provide a storage location, but also tell how big the storage location you provided is.
Thats why you should initialize *addr_len to the buffer size you allocated.
After your call the value pointed to by addrlen will inform you about how much (if any) of the space you allocated to store the source address got actually filled with data.
About sizes
The whole hassle with struct sockaddr and passing sizes back and forth has to do with the fact that even thoug they're most heavily used in networking sockets were intended to be much more general concept.
Think about unix domain sockets as an an example as they are implemented via the filesystem they require an adressing scheme totaly different from that known from IP based networking. The type of sockaddr used here is:
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
sun_path[UNIX_PATH_MAX]; /* pathname */
};
Compare this to the struct used in IP based networking:
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 */
};
it should be clear both don't have too much in common.
sockets were designed to be able to fit both cases.
ssize_t recvfrom(int socket, void *buffer, size_t length, int flags,
struct sockaddr *address, socklen_t *address_len);`
The address_len argument specifies the length of the address structure i.e. the number of bytes to use from the start address indicated at address(start address of memory location + number of bytes from the start address that hold the value)
The structure is defined in /usr/include/bits/socket.h
/* Structure describing a generic socket address. */
struct sockaddr
{
__SOCKADDR_COMMON (sa_); /* Common data: address family and length. */
char sa_data[14]; /* Address data. */
};
Thus the sa_data field holds the address data (start address of the data) whose length is indicated by the address_len argument.
... whenever a function says it takes a struct sockaddr* you can cast your
struct sockaddr_in*, struct sockaddr_in6*, or struct sockadd_storage*
to that type with ease and safety.
Therefore, as indicated in the man page and #WhozCraig in the comment to your question, this field is updated with the actual size when the method returns.
More information
recvfrom
Beej's Guide to Network Programming - struct sockaddr and pals

Checking the address family in socket programming

what will be the output of the following code :
char peer_ip[16];
inet_pton(AF_INET,"127.0.0.1",peer_ip);
now I have peer_ip in network form. How can I check what is the address family ??? I cannot use inet_ntop now. Is there any way ?? Will getaddrinfo work in this case ???
You can't—inet_pton gives you either a struct in_addr (for AF_INET) or a struct in6_addr (for AF_INET6), depending on what address family you pass in. If you consider these structures to be binary blobs of memory, there's no way you can recover the address family from them, you just have to keep track of what type of binary blob you have.
You should really be using a struct in_addr, not a char[16] as the value passed into inet_pton:
struct in_addr peer_ip;
inet_pton(AF_INET, "127.0.0.1", &peer_ip);
You have to go higher up and use getaddrinfo instead of inet_pton (which doesn't handle IPv6 scopes) and instead of opaque buffers use struct sockaddr_storage and struct sockaddr pointers then you can immediately determine the family with ss.ss_family or sa.sa_family as appropriate.

Accept() function; Simple tcp server in C

I'm learning socket programming in C & downloaded a simple tcp server source file. I understand every line except the 2nd parameters in these functions:
accept(socket_fd, (struct sockaddr *)&client, &length);
bind(socket_fd, (struct sockaddr *)&server, length);
The accept + bind functions are the typical functions in "sys/types.h" & "sys/socket.h", and the man page describes it as a pointer to a struct, but I still can't understand what's really going on here.
Can someone please explain what is going on in the second parameter? The brackets, pointer and address symbols are confusing me in the same expression.
Thanks in advance!
The & symbol essentially means "get the address of the value/object". The (struct sockaddr *) is a cast. It tells the compiler that you want to treat the address as a pointer to a sockaddr structure. So together, it is telling the compiler that client can be treated as a sockaddr structure and to pass the address of it to the function. In the case of the accept function, the address of the connecting socket will be stored in the given structure.
What's happening is that accept and bind function are expecting struct sockaddr pointers, and your client and server variables are probably declared as (struct sockaddr *). So, in order to avoid a warning in C or a compiler error in C++, you need an explicit cast which you do by putting the expression:
(struct sockaddr *)
Before your parameter.
And you need the ampersand, because client and server are not pointers. They were probably declared like:
struct sockaddr_in client, server;
It's also worth mentioning that the structures are closely related. Take a look at the picture from Stevens UnP.

Resources