2

For example, I'd like to know if there is any significant difference or good/bad practice

Doing this way:

unsigned int length_addr; 
length_addr = sizeof(cli_addr);

nbytes = recvfrom(sockfd, buffer, sizeof(buffer), 0,
                  (struct sockaddr *)&cli_addr, &length_addr);

and this way:

nbytes = recvfrom(sockfd, buffer, sizeof(buffer), 0,
                  (struct sockaddr *)&cli_addr, sizeof(cli_addr));
chqrlie
  • 131,814
  • 10
  • 121
  • 189
jorge saraiva
  • 235
  • 4
  • 15

2 Answers2

2

Yes, there's a significant difference.

  • For the first case, you are passing the address of an unsigned int, basically an insigned int *.

  • In the second case, you're passing the result of sizeof operator, of type size_t.

They are not the same.

That said, as per the man page, basically both are not correct. The last argument should be of type socklen_t *, so you should better stick to the correct types.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • When do u say "both are not correct", are they 100% incorrect ? why first one isn't correct ? Im passing a reference of unsigned int. The argument socklen_t * can't be an unsigned int? – jorge saraiva Oct 31 '16 at 00:11
  • 1
    @jorgesaraiva, `socklen_t` is one of the types that strongly depend on the architecture size... as they can be implemented as `signed int` (to allow for negative, error values) as `unsigned int` (to allow for large values) and `unsigned long int` (for example, in 64bit architectures, a 64 bit integer) to allow for huge values. You had better to use the proper types, as they are there for your convenience. And indeed more, if you have to cast the pointer to type, instead of the value. This is a common error that leads to many undetected mistakes, very difficult to pursue. – Luis Colorado Nov 01 '16 at 09:49
1

There's actually a difference. As someone said, there's quite a difference between passing an address (first situation) or a (size_t) value (second situation). If you check the recvfrom manual reference you can see that the last argument is a pointer to a memory space which has the size of sockaddr of the previous argument.

#include <sys/socket.h>

ssize_t recvfrom(int socket, void *buffer, size_t length, int flags,
         struct sockaddr *address, socklen_t *address_len);


/*address_len
Specifies the length of the sockaddr structure pointed to by the address argument.*/

The first one is actually correct as you're giving to the lenght_addr the size of the cli_addr and then passing the pointer as the argument. So it should work fine.

Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87