Struct sockaddr, sin_family is not a member

sockets, visual-c++, windows

Solution

In sockets API the address structure to use depends on the protocol. If you are using IPv4, the structure you need is `sockaddr_in`.

The sockets API appeared long ago when `void *` wasn't in standard. Pointers to `sockaddr` are used all over the sockets functions in exactly the same way as we would use `void *` pointers. The functions expect you to pass the pointers to the structures related to protocols you use. The unpleasant thing is that you need a cast whenever you pass a pointer to your address structure, but there is nothing you can do about it.

IPv4 example:

struct sockaddr_in address;

// ...

memset( &address, 0, sizeof(address) );

address.sin_family = AF_INET;
address.sin_port = htons(1100);
address.sin_addr.s_addr = INADDR_ANY;

if ( bind( sock, (struct sockaddr *)&address, sizeof(address) ) < 0 )
{
   //....
}

Problem

According to this article from msdn ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms740496(v=vs.85).aspx) the struct varies depending on which protocol is selected! Now I want to use this code from http://www.intelliproject.net/articles/showArticle/index/check_tcp_udp_port to check if a port is open or not! Now I have the struct sockaddr as follows: ``` struct sockaddr { ushort sa_family; char sa_data[14]; }; ``` but need this strcuture: ``` struct sockaddr { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; ``` Which changes are necessary? (Ws2_32.lib is linked and following includes ``` #define WIN32_LEAN_AND_MEAN // sockets #include "windows.h" #include <winsock2.h> #include <ws2tcpip.h> ``` Thx

Original source