Tommaso Bendinelli
Tommaso Bendinelli

Reputation: 621

Formal Parameters difference between sendto() and recvfrom() in C

I am using recvfrom() and sendto() for receiving and sending UDP packets.

I have noticed that recvfrom() as last parameter requires a pointer to the variable storing the length of server address while sendto() requires the variable that stores the length of the client address.

Why there is this difference?

Upvotes: 3

Views: 236

Answers (2)

Roberto Caboni
Roberto Caboni

Reputation: 7490

Since UDP is not connection based (there's not a connect(sd, ...) call in which you say: from now on all data related to socket descriptor sd will come from a well known IP-port couple), whenever you issue recvfrom() it will (try to) return you the address from where incoming data origins.

It writes the address in src_addr buffer, if it is not NULL. This buffer is provided by the caller and its size must be specified setting addr_len parameter. It is passed by pointer because recvfrom(), after using it to limit the amount of data written in src_addr, will overwrite it with the actual address length. We can say that addr_len is an input-output parameter.

The caller of sendto(), on the other side, will exactly know the destination address, so addr_len in this case is passed by value because is an input-only parameter.

This information is clearly explained in the guide you linked in the question.

Upvotes: 2

kiran Biradar
kiran Biradar

Reputation: 12742

I have noticed that recvfrom() as last parameter requires a pointer to the variable storing the length of server address while sendto() requires the variable that stores the length of the client address.

You actually answering your own question

recvfrom() as last parameter requires a pointer to
the variable storing the length of server address.


while sendto() requires the variable that stores 
the length of the client address.

recvfrom() needs pointer because it is storing the value to the location where that pointer is pointing . Since in c there is nothing called call by reference you need to pass the pointer to simulate call-by-reference behavior.

Upvotes: 3

Related Questions