user15747807
user15747807

Reputation:

In sockets, why do I have to use sizeof(addr) in connect() instead of using (socklen_t)&addr like in accept()?

I'm experimenting with sockets in C++, and I don't understand why in the accept() function the last parameter is:

socklen_t *addr_len

And I can do this:

accept(m_sock, (struct sockaddr *)&addr, (socklen_t *)&addr);

But in the connect() function the last parameter is:

socklen_t addr_len

And i get an error when I do this:

connect(m_sock, (struct sockaddr *)&addr, (socklen_t)&addr);

error: cast from pointer to smaller type 'socklen_t' (aka 'unsigned int') loses information

In that second case, why do I have to use sizeof(addr) instead of (socklen_t)&addr?

Upvotes: 0

Views: 567

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597016

The last parameter of accept() is an input/output parameter passed by pointer. The caller needs to pass in the address of an allocated sockaddr_... buffer in the 2nd parameter, and pass in the address of a socklen_t variable in the 3rd parameter, where that variable specifies the buffer's allocated size. The function will copy the accepted peer's information into the caller's sockaddr_... buffer, being sure not to exceed the specified buffer size. The number of bytes copied to the buffer will be written back to the socklen_t variable upon exit.

socklen_t addr_len = sizeof(addr);
accept(m_sock, (struct sockaddr *)&addr, &addr_len);

The last parameter of connect() is an input-only parameter passed by value. The caller needs to pass in the address of an allocated and populated sockaddr_... buffer in the 2nd parameter, and pass in the value of the buffer's populated size in the 3rd parameter. The function will read from the caller's sockaddr_... buffer, being sure not to exceed the specified buffer size. The function does not write anything back to the caller, so no socklen_t variable is needed (but you can use one if you want to).

connect(m_sock, (struct sockaddr *)&addr, sizeof(addr));

Upvotes: 2

Related Questions