Content

Datatypes

A new data type, SOCKET, has been defined. This is needed because a Windows Sockets application cannot assume that socket descriptors are equivalent to file descriptors as they are in UNIX. Furthermore, in UNIX, all handles, including socket handles, are small, non-negative integers, and some applications make assumptions that this will be true. Windows Sockets handles have no restrictions, other than that the value INVALID_SOCKET is not a valid socket. Socket handles may take any value in the range 0 to INVALID_SOCKET-1.

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 */
};

Functions

socket

The Windows Sockets socket function creates a socket which is bound to a specific service provider.
SOCKET socket( int af, int type, int protocol);
Parameters

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:
TypeExplanation
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.

bind

The Windows Sockets bind function associates a local address with a socket.
int bind( SOCKET s, const struct sockaddr FAR* name, int namelen);
Parameters

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.

closesocket

The Windows Sockets closesocket function closes a socket.
int closesocket( SOCKET s);
Parameters Remarks
This function closes a socket. More precisely, it releases the socket descriptor s, so that further references to s will fail with the error WSAENOTSOCK. If this is the last reference to an underlying socket, the associated naming information and queued data are discarded. Any pending blocking, asynchronous calls issued by any thread in this process are canceled without posting any notification messages, or signaling any event objects. Any pending overlapped send and receive operations (WSASend/WSASendTo/WSARecv/WSARecvFrom with an overlapped socket) issued by any thread in this process are also canceled without setting the event object or invoking the completion routine, if specified. In this case, the pending overlapped operations fail with the error status WSA_OPERATION_ABORTED. An application should always have a matching call to closesocket for each successful call to socket to return socket resources to the system.

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.

connect

The Windows Sockets connect function establishes a connection to a peer.
int connect( SOCKET s, const struct sockaddr FAR* name, int namelen);
Parameters Remarks
This function is used to create a connection to the specified destination. If the socket, s, is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound. For connection-oriented sockets (for example, type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the name space of the socket; for a detailed description, please see bind). When the socket call completes successfully, the socket is ready to send/receive data. If the address field of the name structure is all zeroes, connect will return the error WSAEADDRNOTAVAIL. Any attempt to re-connect an active connection will fail with the error code WSAEISCONN.

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:

  1. Use select to determine the completion of the connection request by checking if the socket is writeable, or
  2. If your application is using WSAAsyncSelect to indicate interest in connection events, then your application will receive an FD_CONNECT notification when the connect operation is complete, or
  3. If your application is using WSAEventSelect to indicate interest in connection events, then the associated event object will be signaled when the connect operation is complete.
For a nonblocking socket, until the connection attempt completes all subsequent calls to connect on the same socket will fail with the error code WSAEALREADY. If the return error code indicates the connection attempt failed (that is, WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application can call connect again for the same socket.

getsockname

The Windows Sockets getsockname function gets the local name for a socket.
int getsockname( SOCKET s, struct sockaddr FAR* name, int FAR* namelen);
Parameters Remarks
getsockname retrieves the current name for the specified socket descriptor in name. It is used on a bound and/or connected socket specified by the s parameter. The local association is returned. This call is especially useful when a connect call has been made without doing a bind first; this call provides the only means by which you can determine the local association which has been set by the system. On return, the namelen argument contains the actual size of the name returned in bytes.

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.

inet_addr

The Windows Sockets inet_addr function converts a string containing an Internet Protocol dotted address into an in_addr structure.
unsigned long inet_addr (const char FAR * cp);
Parameters:

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

inet_ntoa

The Windows Sockets inet_ntoa function converts a network address into a string in dotted format.
char FAR * inet_ntoa( struct in_addr in );
Parameters:

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

gethostbyaddr

The Windows Sockets gethostbyaddr function gets host information corresponding to an address.
struct hostent FAR * gethostbyaddr( const char FAR *addr, int len, int type);
Parameters Remarks
gethostbyaddr returns a pointer to a hostent structure which contains the name(s) and address which correspond to the given address. All strings are null terminated.

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

The Windows Sockets gethostbyname function gets host information corresponding to a hostname.
struct hostent FAR* gethostbyname( const char FAR *name);
Parameters Remarks
gethostbyname returns a pointer to a hostent structure. The contents of this structure correspond to the hostname name. The pointer which is returned points to a structure which is allocated by Windows Sockets. The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, and so the application should copy any information which it needs before issuing any other Windows Sockets function calls.

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.

listen

The Windows Sockets listen function establishes a socket to listen for an incoming connection.
int listen( SOCKET s, int backlog);
Parameters Remarks
To accept connections, a socket is first created with socket, a backlog for incoming connections is specified with listen, and then the connections are accepted with accept. listen applies only to sockets that are connection oriented, for example, those of type SOCK_STREAM. The socket s is put into "passive" mode where incoming connection requests are acknowledged and queued pending acceptance by the process.

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.

accept

The Windows Sockets accept function accepts a connection on a socket.
SOCKET accept( SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen);
Parameters Remarks
This routine extracts the first connection on the queue of pending connections on s, creates a new socket and returns a handle to the new socket. The newly created socket has the same properties as s including asynchronous events registered with WSAAsyncSelect or with WSAEventSelect, but not including the listening socket's group ID, if any. If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept blocks the caller until a connection is present. If the socket is marked nonblocking and no pending connections are present on the queue, accept returns an error. The accepted socket cannot be used to accept more connections. The original socket remains open.

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.

sendto

The Windows Sockets sendto function sends data to a specific destination.
int sendto(SOCKET s, const char FAR * buf, int len, int flags, const struct sockaddr FAR * to, int tolen);
Parameters Remarks
sendto is used to write outgoing data on a socket. For message-oriented sockets, care must be taken not to exceed the maximum packet size of the underlying subnets, which can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.

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.

recvfrom

The Windows Sockets recvfrom function receives a datagram and stores the source address.
int recvfrom(SOCKET s, char FAR* buf, int len, int flags, struct sockaddr FAR* from, int FAR* fromlen);
Parameters Remarks
This function is used to read incoming data on a (possibly connected) socket and capture the address from which the data was sent.
For stream-oriented sockets such as those of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application can use the ioctlsocket SIOCATMARK to determine whether any more out-of-band data remains to be read. The from and fromlen parameters are ignored for connection-oriented sockets.

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.

setsockopt

The Windows Sockets setsockopt function sets a socket option.
int setsockopt(SOCKET s, int level, int optname, const char FAR * optval, int optlen);
Parameters Remarks
setsockopt sets the current value for a socket option associated with a socket of any type, in any state. Although options can exist at multiple protocol levels, they are always present at the uppermost "socket'' level. Options affect socket operations, such as whether expedited data is received in the normal data stream, whether broadcast messages can be sent on the socket.
There are two types of socket options: Boolean options that enable or disable a feature or behavior, and options which require an integer value or structure. To enable a Boolean option, optval points to a nonzero integer. To disable the option optval points to an integer equal to zero. optlen should be equal to sizeof(int) for Boolean options. For other options, optval points to the an integer or structure that contains the desired value for the option, and optlen is the length of the integer or structure.

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.

  • SO_DEBUG
  • SO_GROUP_PRIORITY
  • SO_KEEPALIVE
  • SO_LINGER
  • SO_REUSEADDR
  • SO_RCVBUF
  • SO_SNDBUF
  • PVD_CONFIG
  • TCP_NODELAY
    Return Values
    If no error occurs, setsockopt returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.