Winsock Structures
This section details the fundamental data structures used by the Windows Sockets API (Winsock) to manage network communication.
SOCKADDR
and SOCKADDR_IN
The SOCKADDR
structure is a generic address structure used by Winsock. The SOCKADDR_IN
structure is a specific implementation for Internet Protocol version 4 (IPv4) addresses.
struct sockaddr {
u_short sa_family; // Address family
char sa_data[14]; // Up to 14 bytes of the socket address
};
struct sockaddr_in {
short int sin_family; // Address family (AF_INET)
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
char sin_zero[8]; // Not used
};
sa_family
: Specifies the address family. For IPv4, this is AF_INET
.
sin_port
: The port number, in network byte order.
sin_addr
: An in_addr
structure containing the IPv4 address.
IN_ADDR
The IN_ADDR
structure represents an IPv4 address.
struct in_addr {
union {
struct {
u_char s_b1, s_b2, s_b3, s_b4;
} S_un_b;
struct {
u_short s_w1, s_w2;
} S_un_w;
u_long S_addr;
} S_un;
};
S_addr
: Stores the IPv4 address as a 32-bit unsigned integer, in network byte order.
WSAPOLLFD
The WSAPOLLFD
structure is used with the WSAPoll
function to specify a set of file descriptors to monitor for readiness.
typedef struct wsapollfd {
SOCKET fd;
short events;
short revents;
} WSAPOLLFD, *PWSAPOLLFD;
fd
: The socket descriptor.
events
: The events to monitor (e.g., POLLIN
, POLLOUT
).
revents
: The events that have occurred.
TIMEVAL
The TIMEVAL
structure is used for specifying time-out values for blocking socket operations.
struct timeval {
long tv_sec; // Seconds
long tv_usec; // Microseconds
};
tv_sec
: The number of seconds.
tv_usec
: The number of microseconds.
FD_SET
The FD_SET
structure (or rather, a macro that manages an array of SOCKET
descriptors) is used with select()
to specify a set of sockets to monitor for read, write, or exceptional conditions.
Note: While conceptually a structure, FD_SET
is typically implemented as an opaque type and manipulated via macros.
Key macros:
FD_ZERO(fdset)
: Clears all socket descriptors from the set.FD_SET(s, fdset)
: Adds a socket descriptor to the set.FD_CLR(s, fdset)
: Removes a socket descriptor from the set.FD_ISSET(s, fdset)
: Checks if a socket descriptor is in the set.
Other Important Structures
Winsock employs various other structures for specific purposes, including:
WSABUF
: Used for buffer management in asynchronous operations.WSAOVERLAPPED
: Manages asynchronous I/O operations.linger
: Controls socket linger behavior.GROUP_REQ
andGROUP_SOURCE_REQ
: For multicast group management.