WSAEFAULT error when using getsockname function

I have a problem using getsockname function. I have this code:

 struct sockaddr sa; int sa_len; sa_len = sizeof(sa); if (getsockname(socketfd, &sa, &sa_len) != SOCKET_ERROR) { /// } else { int error = WSAGetLastError(); //error here WSAEFAULT always } 

As you can see, I always have an error when using the getsockname function. The error is WSAEFAULT . But why? structure and structure are correct, why is this happening?

WSAEFAULT desc:

The namelen or namelen parameter is not a valid part of the user address space, or the namelen parameter is too small.

ps application has 64 bit

Thanks!

+4
source share
2 answers

Your struct sockaddr too small to accept a socket address. Use either a structure of the appropriate size, such as struct sockaddr_in , or better yet, use struct sockaddr_storage , which is guaranteed to be large enough to contain the address. Using sockaddr_storage also allows you to easily support both IPv4 and IPv6 with minimal settings.

Edited Code:

 struct sockaddr_storage sa; int sa_len; sa_len = sizeof(sa); if (getsockname(socketfd, (struct sockaddr *)&sa, &sa_len) != SOCKET_ERROR) 
+4
source

Instead of the general sockaddr structure, use the one specified for your protocol ie * struct sockaddr_in * for the IPv4 address. See here for a complete example.

+1
source

All Articles