Accept() function; Simple tcp server in C - 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.

Related

Why does the accept() call uses an empty sockaddr structure?

I just got asked this question and couldn't answer it, I looked at how I've been coding it and was really confused.
This is how I have been programming the accept() call in a server:
struct sockaddr_in client;
size=sizeof(client);
if(( nds=accept(ds,(struct sockaddr*)&client,&size)) <0)
{
perror("accept");
close(ds);
exit(-1);
}
Where ds is socket descriptor
I know the second parameter of accept is a pointer to the struct but don't know why it should be empty.
Weel, it is an output parameter, you can send it or not, but when you send it, it will be filled with the the connecting socket.
Take a look here http://pubs.opengroup.org/onlinepubs/009695399/functions/accept.html
If address is not a null pointer, the address of the peer for the
accepted connection shall be stored in the sockaddr structure pointed
to by address, and the length of this address shall be stored in the
object pointed to by address_len.

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 does recvfrom care about who the data comes from

So, I'm creating a server in C which uses UDP, and I want to listen for incoming packets from many sources. Therefore, when I call ssize_t recvfrom(int, void *, size_t, int, struct sockaddr * __restrict, socklen_t * __restrict), the 5th parameter, that which contains the sender's information, may vary.
Is there a way to receive the packets without knowing each individual client's address information? And, is this possible with C's library?
Here's my code:
int file_descriptor;
char data[1024];
int bytes_recved;
sockaddr_in iDontKnow;
socklen_t addr_len = sizeof(iDontKnow);
if ((bytes_recved = recvfrom(file_descriptor, data, strlen(data), 0, (struct sockaddr*)&iDontKnow, &addr_len)) < 0) {
perror("Failed to receive data");
}
I noticed that when receiving data with Java's DatagramSocket and DatagramPacket classes, the DatagramSocket's receive function took in a parameter of type DatagramPacket. This DatagramPacket, however, only held the object in which to place the data. So, why does C's implementation of UDP receiving require that you know the sender's information?
Is there a way to receive the packets without knowing each individual client's address information?
Well, you don't need to know the sender information beforehand, anyway. Once a packet is received, the sender information (if available) will be stored into address.
From the man page,
ssize_t recvfrom(int socket, void *restrict buffer, size_t length,
int flags, struct sockaddr *restrict address,
socklen_t *restrict address_len);
[...] If the address argument is not a null pointer and the protocol provides the source address of messages, the source address of the received message shall be stored in the sockaddr structure pointed to by the address argument, and the length of this address shall be stored in the object pointed to by the address_len argument.
Regarding the why part, in case of connectionless sockets, unless you know of the sender address for a packet in a communication, you cannot reply or respond to the sender. So, it is required to know the sender info specifically in connectionless mode and there comes recvfrom() which, along with the received data, gives us the info about the sender, also.
EDIT:
In your code
recvfrom(file_descriptor, data, strlen(data), 0, (struct sockaddr*)&iDontKnow, &addr_len)
is wrong, as strlen(data) is UB, as you're trying to count the length of an uninitialized char array, which is not qualified to be a string. It invokes undefined behavior. You may want to use sizeof(data), as data is an array.
In case you're not interested in sender's info, just pass a NULL as the corresponding argument.
To add to that, for connectionless sockets (UDP), it's actually required to get the sender information. For connection oriented sockets, you have another stripped-down alternative , recv() which only takes care of receiving and storing the data.
This DatagramPacket, however, only held the object in which to place the data.
And the source address and port, and the length of the data.
So, why does C's implementation of UDP receiving require that you know the sender's information?
It doesn't. It has the option to tell you the source address and port. It's a result parameter, not an input.
You compare different functions from Java and C.
In C there is also a recv() function that does not provide any address.
The sole puprpose of recvfrom over recv is to get the sender's address.
Normally servers reply to packets that they receive. Wihout an address that is not possible.
If you do not care about the sender of your packets, just take recv.
Or to put it the other way around:
If you don't care about the sender, why did you pick the recvfrom version of recv?
I wonder what does the server server if it doesn't care about the client's addresses... But that is not related to your question.
You could do it like these,
int sockfd_recv;
struct sockaddr_in recvaddr;
bzero(&recvaddr, sizeof(recvaddr));
recvaddr.sin_family = AF_INET;
recvaddr.sin_port = htons(port_recv);
recvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(sockfd_recv, (struct sockaddr *)&recvaddr, sizeof(recvaddr));

How sockaddr holds sockaddr_storage or sockaddr_in6?

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

"lvalue required as unary '&' operand" in accept() socket system call

I am writing a network program where, in the server part, I want to accept connections from multiple clients using a listening socket. So I declare an array of address structs like this:
struct sockaddr_in* client;
which I create using malloc and later on, to accept connections I type:
newsock = accept(fd_skt, (struct sockaddr *)&client[i], &(sizeof(client[i])));
and there I get "lvalue required as unary '&' operand" from the compiler. Can anyone figure out what I have done wrong?
Yes, you can't take the address of something that isn't an lvalue, that is an object with an address. The result of the sizeof operator is just a value, it isn't an object with an address.
You need to create a local variable so that you can take its address.
E.g.
socklen_t addrlen = sizeof client[i];
newsock = accept(fd_skt, (struct sockaddr *)&client[i], &addrlen));
As an aside, struct sockaddr_in* client; declares a pointer, not an array. To use client as an array you need to assign it to a dynamically allocated array at some point before the call to accept. I assume that this is what you are doing when you say "I create using malloc".
Alternatively you could actually declare client as an array.
struct sockaddr_in client[MAX_CLIENTS];
Charles' answer is correct, but one way to get around this kind of obnoxious function interface that requires a pointer to a value you plan to just throw away is to use compound literals:
newsock = accept(fd_skt, (struct sockaddr *)&client[i], (socklen_t[]){sizeof client[0]});

Resources