Because the SOCKET type is unsigned, compiling existing source code from, for example, a UNIX environment may lead to compiler warnings about signed/unsigned data type mismatches.
This is a general socket structure:
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
The sockaddr structure varies depending on the the protocol selected. The structure below is used with TCP/IP. Other protocols use similar structures.
struct sockaddr_in {
short sin_family; /* protocol family (either AF_INET or PF_INET) */
u_short sin_port; /* port number */
struct in_addr sin_addr; /* IP address */
char sin_zero[8]; /* unused */
};
Internet address is basically a 4-byte number; that is, for modern Intel processors it can be stored in a type of int or long int (which is the same as int). However, before int type took only 2 bytes and the IP addresses were stored in long int variables. The following structure is a structure for storing an IP address. For more convenience it's defined as a union. That gives us access to each byte of the IP 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;
#define s_addr S_un.S_addr
/* can be used for most tcp & ip code */
#define s_host S_un.S_un_b.s_b2
/* host on imp */
#define s_net S_un.S_un_b.s_b1
/* network */
#define s_imp S_un.S_un_w.s_w2
/* imp */
#define s_impno S_un.S_un_b.s_b4
/* imp # */
#define s_lh S_un.S_un_b.s_b3
/* logical host */
};
This is a structure for information from DNS sites about other hosts:
struct hostent {
char FAR * h_name; /* official name of host */
char FAR * FAR * h_aliases; /* alias list */
short h_addrtype; /* host address type */
short h_length; /* length of address */
char FAR * FAR * h_addr_list; /* list of addresses */
#define h_addr h_addr_list[0] /* address, for backward compat */
};
Remarks
The socket function causes a socket descriptor and any related resources to be allocated and bound to a specific
transport service provider. Windows Sockets will utilize the first available service provider that supports the
requested combination of address family, socket type and protocol parameters. Note that the socket created will have
the overlapped attribute. Sockets without the overlapped attribute can only be created by using WSASocket.
Note
The manifest constant AF_UNSPEC continues to be defined in the header file but its use is strongly
discouraged, as this can cause ambiguity in interpreting the value of the protocol parameter.
The following are the only two type specifications supported for Windows Sockets 1.1:
| Type | Explanation |
|---|---|
| SOCK_STREAM | Provides sequenced, reliable, two-way, connection-based byte streams with an out-of-band data transmission mechanism. Uses TCP for the Internet address family. |
| SOCK_DGRAM | Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family. |
Return Values
If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of
INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.
Remarks
This routine is used on an unconnected connectionless or connection-oriented socket, before subsequent connects or
listens. When a socket is created with socket, it exists in a name space (address family), but it has no name assigned.
bind establishes the local association of the socket by assigning a local name to an unnamed socket.
As an example, in the Internet address family, a name consists of three parts: the address family, a host address,
and a port number which identifies the application. In Windows Sockets 2, the name parameter is not strictly
interpreted as a pointer to a "sockaddr" structure. It is cast this way for Windows Sockets compatibility. Service
Providers are free to regard it as a pointer to a block of memory of size namelen. The first two bytes in
this block (corresponding to "sa_family" in the "sockaddr" declaration) must contain the address family that was used
to create the socket. Otherwise, an error WSAEFAULT will occur.
If an application does not care what local address is assigned to it, it can specify the manifest constant value ADDR_ANY for the sa_data field of the name parameter. This allows the underlying service provider to use any appropriate network address, potentially simplifying application programming in the presence of multihomed hosts (that is, hosts that have more than one network interface and address). For TCP/IP, if the port is specified as zero, the service provider will assign a unique port to the application with a value between 1024 and 5000. The application can use getsockname after bind to learn the address and the port that has been assigned to it, but note that if the Internet address is equal to INADDR_ANY, getsockname will not necessarily be able to supply the address until the socket is connected, since several addresses can be valid if the host is multihomed.
Return Values
If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be
retrieved by calling WSAGetLastError.
Return Values
If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned,
and a specific error code can be retrieved by calling WSAGetLastError.
For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a default destination address which will be used on subsequent send/WSASend and recv/WSARecv calls. Any datagrams received from an address other than the destination address specified will be discarded. If the address field of the name structure is all zeroes, the socket will be "dis-connected." Then, the default remote address will be indeterminate, so send/WSASend and recv/WSARecv calls will return the error code WSAENOTCONN. However, sendto/WSASendTo and recvfrom/WSARecvFrom can still be used. The default destination can be changed by simply calling connect again, even if the socket is already "connected". Any datagrams queued for receipt are discarded if name is different from the previous connect.
For connectionless sockets, name can indicate any valid address, including a broadcast address. However, to connect to a broadcast address, a socket must have setsockopt SO_BROADCAST enabled. Otherwise, connect will fail with the error code WSAEACCES.
Comments
When connected sockets break (that is, become closed for whatever reason), they should be discarded and recreated. It is
safest to assume that when things go awry for any reason on a connected socket, the application must discard and
recreate the needed sockets in order to return to a stable point.
Return Values
If no error occurs, connect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error
code can be retrieved by calling WSAGetLastError.
On a blocking socket, the return value indicates success or failure of the connection attempt.
With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return SOCKET_ERROR, and WSAGetLastError will return WSAEWOULDBLOCK. In this case, the application can:
If a socket was bound to an unspecified address (for example, ADDR_ANY), indicating that any of the host's addresses within the specified address family should be used for the socket, getsockname will not necessarily return information about the host address, unless the socket has been connected with connect or accept. A Windows Sockets application must not assume that the address will be specified unless the socket is connected. This is because for a multihomed host the address that will be used for the socket is unknown unless the socket is connected.
Return Values
If no error occurs, getsockname returns zero. Otherwise, a value of SOCKET_ERROR is returned, and
a specific error code can be retrieved by calling WSAGetLastError.
Remarks:
This function interprets the character string specified by the cp parameter. This string represents a numeric
Internet address expressed in the Internet standard ".'' notation. The value returned is a number suitable for use as an
Internet address. All Internet addresses are returned in IP's network order (bytes ordered from left to right).
Internet Addresses:
Values specified using the "." notation take one of the following forms:
a.b.c.d a.b.c a.b a
When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes
of an Internet address. Note that when an Internet address is viewed as a 32-bit integer quantity on the Intel
architecture, the bytes referred to above appear as "d.c.b.a". That is, the bytes on an Intel processor are ordered from
right to left.
Note
The following notations are only used by Berkeley, and nowhere else on the Internet. In the interests of
compatibility with their software, they are supported as specified.
Return Values
If no error occurs, inet_addr returns an unsigned long containing a suitable binary representation of the
Internet address given. If the passed-in string does not contain a legitimate Internet address, for example if a
portion of an "a.b.c.d" address exceeds 255, inet_addr returns the value INADDR_NONE.
See Also: inet_ntoa
Remarks
This function takes an Internet address structure specified by the in parameter. It returns an ASCII string
representing the address in "." notation as "a.b.c.d". Note that the string returned by inet_ntoa resides
in memory which is allocated by Windows Sockets. The application should not make any assumptions about the way in which
the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the
same thread, but no longer.
Return Values
If no error occurs, inet_ntoa returns a char pointer to a static buffer containing the text address in
standard "." notation. Otherwise, it returns NULL. The data should be copied before another Windows Sockets
call is made.
See Also: inet_addr
Return Values
If no error occurs, gethostbyaddr returns a pointer to the hostent structure described above.
Otherwise, it returns a NULL pointer and a specific error number can be retrieved by calling
WSAGetLastError.
gethostbyname does not resolve IP address strings passed to it. Such a request is treated exactly as if an unknown host name were passed. An application with an IP address string to resolve should use inet_addr to convert the string to an IP address, then gethostbyaddr to obtain the hostent structure.
gethostbyname will resolve the string returned by a successful call to gethostname.
Return Values
If no error occurs, gethostbyname returns a pointer to the hostent structure described above. Otherwise,
it returns a NULL pointer and a specific error number can be retrieved by calling WSAGetLastError.
This function is typically used by servers that could have more than one connection request at a time: if a connection request arrives with the queue full, the client will receive an error with an indication of WSAECONNREFUSED.
listen attempts to continue to function rationally when there are no available descriptors. It will accept connections until the queue is emptied. If descriptors become available, a later call to listen or accept will refill the queue to the current or most recent "backlog", if possible, and resume listening for incoming connections.
An application can call listen more than once on the same socket. This has the effect of updating the current backlog for the listening socket. Should there be more pending connections than the new backlog value, the excess pending connections will be reset and dropped.
Compatibility
The backlog parameter is limited (silently) to a reasonable value as determined by the underlying service provider.
Illegal values are replaced by the nearest legal value.
Return Values
If no error occurs, listen returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a
specific error code can be retrieved by calling WSAGetLastError.
The argument addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. This call is used with connection-oriented socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.
Return Values
If no error occurs, accept returns a value of type SOCKET which is a descriptor for the accepted
socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by
calling WSAGetLastError.
The integer referred to by addrlen initially contains the amount of space pointed to by addr. On return it will contain the actual length in bytes of the address returned.
The to parameter can be any valid address in the socket's address family, including a broadcast or any multicast address. To send to a broadcast address, an application must have setsockopt SO_BROADCAST enabled. Otherwise, sendto will fail with the error code WSAEACCES. For TCP/IP, an application can send to any multicast address (without becoming a group member).
If the socket is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound. An application can use getsockname to determine the local socket name in this case. Note that the successful completion of a sendto does not indicate that the data was successfully delivered. sendto is normally used on a connectionless socket to send a datagram to a specific peer socket identified by the to parameter. Even if the connectionless socket has been previously connected to a specific address, to overrides the destination address for that particular datagram only. On a connection-oriented socket, the to and tolen parameters are ignored; in this case, the sendto is equivalent to send.
For sockets using IP:
To send a broadcast (on a SOCK_DGRAM only), the address in the to parameter should be constructed using the
special IP address INADDR_BROADCAST (defined in WINSOCK2.H) together with the intended port number. It is
generally inadvisable for a broadcast datagram to exceed the size at which fragmentation can occur, which implies that the
data portion of the datagram (excluding headers) should not exceed 512 bytes.
If no buffer space is available within the transport system to hold the data to be transmitted, sendto will
block unless the socket has been placed in a nonblocking I/O mode. On nonblocking stream-oriented sockets, the number of
bytes written can be between 1 and the requested length, depending on buffer availability on both the local and foreign
hosts. The select, WSAAsyncSelect or WSAEventSelect call can be used to determine when it is possible
to send more data.
Calling sendto with a len of zero is legal and, in this case, sendto will return
zero as a valid return value. For message-oriented sockets, a zero-length transport datagram is sent.
Flags can be used to influence the behavior of the function invocation beyond the options specified for the associated socket.
That is, the semantics of this function are determined by the socket options and the flags parameter. The latter is
constructed by or-ing any of the following values:
| Value | Meaning |
| MSG_DONTROUTE | Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag. |
| MSG_OOB | Send out-of-band data (stream-style socket such as SOCK_STREAM only. Also see Out-Of-Band data for a discussion of this topic.) |
Return Values
If no error occurs, sendto returns the total number of bytes sent. (Note that this can be less than the number
indicated by len.) Otherwise, a value of SOCKET_ERROR is returned, and a specific error code
can be retrieved by calling WSAGetLastError.
For message-oriented sockets, data is extracted from the first enqueued message, up to the size of the buffer supplied.
If the datagram or message is larger than the buffer supplied, the buffer is filled with the first part of the datagram,
and recvfrom generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost.
If from is nonzero, and the socket is not connection oriented (for example, type SOCK_DGRAM), the network address
of the peer which sent the data is copied to the corresponding struct sockaddr. The value pointed to by
fromlen is initialized to the size of this structure, and is modified on return to indicate the actual
size of the address stored there.
If no incoming data is available at the socket, the recvfrom call waits for data to arrive unless the socket is
nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The
select, WSAAsyncSelect, or WSAEventSelect can be used to determine when more data arrives.
If the socket is connection oriented and the remote side has shut down the connection gracefully, a recvfrom
will complete immediately with zero bytes received. If the connection has been reset recvfrom will fail with the
error WSAECONNRESET.
Flags can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by or-ing any of the following values: Value Meaning MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue. MSG_OOB Process out-of-band data. (See section Out-Of-Band data for a discussion of this topic.)
Return Values
If no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed,
the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be
retrieved by calling WSAGetLastError.
The following options are supported for setsockopt. The Type identifies the type of data addressed by optval.
| level = SOL_SOCKET | ||
|---|---|---|
| Value | Type | Meaning |
| SO_BROADCAST | BOOL | Allow transmission of broadcast messages on the socket. |
| SO_DEBUG | BOOL | Record debugging information. |
| SO_DONTLINGER | BOOL | Do not block close waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set to zero. |
| SO_DONTROUTE | BOOL | Do not route: send directly to interface. |
| SO_GROUP_PRIORITY | int | Specify the relative priority to be established for sockets that are part of a socket group. |
| SO_KEEPALIV | BOOL | Send keepalives |
| SO_LINGE | struct linger | Linger on close if unsent data is present |
| SO_OOBINLINE | BOOL | Receive out-of-band data in the normal data stream. (See section Out-Of-Band data for a discussion of this topic.) |
| SO_RCVBUF | int | Specify buffer size for receives |
| SO_REUSEADDR | BOOL | Allow the socket to be bound to an address which is already in use. (See bind.) |
| SO_SNDBUF | int | Specify buffer size for sends. |
| PVD_CONFIG | Service Provider Dependent | This object stores the configuration information for the service provider associated with socket s. The exact format of this data structure is service provider specific. |
| level = IPPROTO_TCP | ||
| TCP_NODELAY | BOOL | Disables the Nagle algorithm for send coalescing. |
struct linger {
u_short l_onoff;
u_short l_linger;
}
To enable SO_LINGER, the application should set l_onoff to a nonzero value, set
l_linger to zero or the desired time-out (in seconds), and call setsockopt. To
enable SO_DONTLINGER (that is, disable SO_LINGER) l_onoff should be set to zero
and setsockopt should be called. Note that enabling SO_LINGER with a nonzero time-out on a
nonblocking socket is not recommended.