4.1 Socket Routines

This chapter presents the socket library routines in alphabetical order, and describes each routine in detail.

In each routine it is indicated that the header file winsock.h must be included. Appendix A.2 lists the Berkeley-compatible header files which are supported. These are provided for compatibility purposes only, and each of them will simply include winsock.h. The Windows header file windows.h is also needed, but winsock.h will include it if necessary.

4.1.1 accept()

Description

Accept a connection on a socket

#include <winsock.h>

SOCKET PASCAL FAR accept ( SOCKET s, struct sockaddr FAR * addr,

int FAR * addrlen );


s

A descriptor identifying a socket which is listening for connections after a listen().

addr

An optional pointer to a buffer which receives the address of the connecting entity, as known to the communications layer. The exact format of the addr argument is determined by the address family established when the socket was created.

addrlen

An optional pointer to an integer which contains the length of the address addr.


Remarks

This routine extracts the first connection on the queue of pending connections on s, creates a new socket with the same properties as s and returns a handle to the new socket. If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept() returns an error as described below. The accepted socket may not 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-based 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 Value

If no error occurs, accept() returns a value of type SOCKET which is a descriptor for the accepted packet. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code may 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.


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT

WSAEINTR

WSAEINPROGRESS

WSAEINVAL

WSAEMFILE
WSAENOBUFS
WSAENOTSOCK
WSAEOPNOTSUPP
WSAEWOULDBLOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The addrlen argument is too small (less than the sizeof a struct sockaddr).
The (blocking) call was canceled via WSACancelBlockingCall().
A blocking Windows Sockets call is in progress.
listen() was not invoked prior to accept().
The queue is empty upon entry to accept() and there are no descriptors available.
No buffer space is available.
The descriptor is not a socket.
The referenced socket is not a type that supports connection-oriented service.
The socket is marked as non-blocking and no connections are present to be accepted.


See Also

bind(), connect(), listen(), select(), socket(), WSAAsyncSelect()


4.1.2 bind()

Description

Associate a local address with a socket.

#include <winsock.h>

int PASCAL FAR bind ( SOCKET s, const struct sockaddr FAR * name, int namelen );


s

A descriptor identifying an unbound socket.

name

The address to assign to the socket. The sockaddr structure is defined as follows:


struct sockaddr {

u_short sa_family;

char sa_data[14];

};

namelen

The length of the name.


Remarks

This routine is used on an unconnected datagram or stream socket, before subsequent connect()s or listen()s. 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 (host address/port number) of the socket by assigning a local name to an unnamed socket.


In the Internet address family, a name consists of several components. For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts: a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application. If an application does not care what address is assigned to it, it may specify an Internet address equal to INADDR_ANY, a port equal to 0, or both. If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence of multi-homed hosts. If the port is specified as 0, the Windows Sockets implementation will assign a unique port to the application with a value between 1024 and 5000. The application may use getsockname() after bind() to learn the address that has been assigned to it, but note that getsockname() will not necessarily fill in the Internet address until the socket is connected, since several Internet addresses may be valid if the host is multi-homed.

If an application desires to bind to an arbitrary port outside of the range 1024 to 5000, such as the case of rsh which must bind to any reserved port, code similar to the following may be used:


    SOCKADDR_IN sin;
    SOCKET s;
    u_short alport = IPPORT_RESERVED;

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    for (;;) {
        sin.sin_port = htons(alport);
        if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0) {
            /* it worked */
        }
        if ( GetLastError() != WSAEADDRINUSE) {
            /* fail */
        }
        alport--;
        if (alport == IPPORT_RESERVED/2 ) {
            /* fail--all unassigned reserved ports are */
            /* in use. */
        }
    }

Return Value

If no error occurs, bind() returns 0. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEADDRINUSE


WSAEFAULT

WSAEINPROGRESS
WSAEAFNOSUPPORT

WSAEINVAL
WSAENOBUFS

WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The specified address is already in use. (See the SO_REUSEADDR socket option under setsockopt().)
The namelen argument is too small (less than the size of a struct sockaddr).
A blocking Windows Sockets call is in progress.
The specified address family is not supported by this protocol.
The socket is already bound to an address.
Not enough buffers available, too many connections.
The descriptor is not a socket.


See Also

connect(), listen(), getsockname(), setsockopt(), socket(), WSACancelBlockingCall().


4.1.3 closesocket()

Description

Close a socket.

#include <winsock.h>

int PASCAL FAR closesocket ( SOCKET s );


s

A descriptor identifying a socket.


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 the underlying socket, the associated naming information and queued data are discarded.


The semantics of closesocket() are affected by the socket options SO_LINGER and SO_DONTLINGER as follows:

Option

Interval

Type of close

Wait for close?


SO_DONTLINGER

Don't care

Graceful

No

SO_LINGER

Zero

Hard

No

SO_LINGER

Non-zero

Graceful

Yes


If SO_LINGER is set (i.e. the l_onoff field of the linger structure is non-zero; see sections 2.4, 4.1.7 and 4.1.21) with a zero timeout interval (l_linger is zero), closesocket() is not blocked even if queued data has not yet been sent or acknowledged. This is called a "hard" or "abortive" close, because the socket's virtual circuit is reset immediately, and any unsent data is lost. Any recv() call on the remote side of the circuit will fail with WSAECONNRESET.

If SO_LINGER is set with a non-zero timeout interval, the closesocket() call blocks until the remaining data has been sent or until the timeout expires. This is called a graceful disconnect. Note that if the socket is set to non-blocking and SO_LINGER is set to a non-zero timeout, the call to closesocket() will fail with an error of WSAEWOULDBLOCK.

If SO_DONTLINGER is set on a stream socket (i.e. the l_onoff field of the linger structure is zero; see sections 2.4, 4.1.7 and 4.1.21), the closesocket() call will return immediately. However, any data queued for transmission will be sent if possible before the underlying socket is closed. This is also called a graceful disconnect. Note that in this case the Windows Sockets implementation may not release the socket and other resources for an arbitrary period, which may affect applications which expect to use all available sockets.

Return Value

If no error occurs, closesocket() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAENOTSOCK
WSAEINPROGRESS
WSAEINTR

WSAEWOULDBLOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The descriptor is not a socket.
A blocking Windows Sockets call is in progress.
The (blocking) call was canceled via WSACancelBlockingCall().
The socket is marked as nonblocking and SO_LINGER is set to a nonzero timeout value.


See Also

accept(), socket(), ioctlsocket(), setsockopt(), WSAAsyncSelect().


4.1.4 connect()

Description

Establish a connection to a peer.

#include <winsock.h>

int PASCAL FAR connect ( SOCKET s, const struct sockaddr FAR * name, int namelen );


s

A descriptor identifying an unconnected socket.

name

The name of the peer to which the socket is to be connected.

namelen

The length of the name.


Remarks

This function is used to create a connection to the specified foreign association. The parameter s specifies an unconnected datagram or stream socket If the socket is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound. Note that if the address field of the name structure is all zeroes, connect() will return the error WSAEADDRNOTAVAIL.


For stream sockets (type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the name space of the socket). When the socket call completes successfully, the socket is ready to send/receive data.

For a datagram socket (type SOCK_DGRAM), a default destination is set, which will be used on subsequent send() and recv() calls.

Return Value

If no error occurs, connect() returns 0. Otherwise, it returns SOCKET_ERROR, and a specific error code may be retrieved by calling WSAGetLastError().
On a blocking socket, the return value indicates success or failure of the connection attempt.
On a non-blocking socket, if the return value is SOCKET_ERROR an application should call WSAGetLastError(). If this indicates an error code of WSAEWOULDBLOCK, then your application can either:

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 the message-based WSAAsyncSelect() to indicate interest in connection events, then your application will receive an FD_CONNECT message when the connect operation is complete.


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEADDRINUSE
WSAEINTR

WSAEINPROGRESS
WSAEADDRNOTAVAIL

WSAEAFNOSUPPORT

WSAECONNREFUSED
WSAEDESTADDREQ
WSAEFAULT
WSAEINVAL
WSAEISCONN
WSAEMFILE
WSAENETUNREACH

WSAENOBUFS

WSAENOTSOCK
WSAETIMEDOUT

WSAEWOULDBLOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The specified address is already in use.
The (blocking) call was canceled via WSACancelBlockingCall().
A blocking Windows Sockets call is in progress.
The specified address is not available from the local machine.
Addresses in the specified family cannot be used with this socket.
The attempt to connect was forcefully rejected.
A destination address is required.
The namelen argument is incorrect.
The socket is not already bound to an address.
The socket is already connected.
No more file descriptors are available.
The network can't be reached from this host at this time.
No buffer space is available. The socket cannot be connected.
The descriptor is not a socket.
Attempt to connect timed out without establishing a connection
The socket is marked as non-blocking and the connection cannot be completed immediately. It is possible to select() the socket while it is connecting by select()ing it for writing.


See Also

accept(), bind(), getsockname(), socket(), select() and WSAAsyncSelect().


4.1.5 getpeername()

Description

Get the address of the peer to which a socket is connected.

#include <winsock.h>

int PASCAL FAR getpeername ( SOCKET s, struct sockaddr FAR * name, int FAR * namelen );


s

A descriptor identifying a connected socket.

name

The structure which is to receive the name of the peer.

namelen

A pointer to the size of the name structure.


Remarks

getpeername() retrieves the name of the peer connected to the socket s and stores it in the struct sockaddr identified by name. It is used on a connected datagram or stream socket.
On return, the namelen argument contains the actual size of the name returned in bytes.

Return Value

If no error occurs, getpeername() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT
WSAEINPROGRESS
WSAENOTCONN
WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The namelen argument is not large enough.
A blocking Windows Sockets call is in progress.
The socket is not connected.
The descriptor is not a socket.


See Also

bind(), socket(), getsockname().


4.1.6 getsockname()

Description

Get the local name for a socket.

#include <winsock.h>

int PASCAL FAR getsockname ( SOCKET s, struct sockaddr FAR * name, int FAR * namelen );


s

A descriptor identifying a bound socket.

name

Receives the address (name) of the socket.

namelen

The size of the name buffer.


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 INADDR_ANY, indicating that any of the host's IP addresses should be used for the socket, getsockname() will not necessarily return information about the host IP address, unless the socket has been connected with connect() or accept(). A Windows Sockets application must not assume that the IP address will be changed from INADDR_ANY unless the socket is connected. This is because for a multi-homed host the IP address that will be used for the socket is unknown unless the socket is connected.

Return Value

If no error occurs, getsockname() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT
WSAEINPROGRESS

WSAENOTSOCK
WSAEINVAL

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The namelen argument is not large enough.
A blocking Windows Sockets operation is in progress.
The descriptor is not a socket.
The socket has not been bound to an address with bind().


See Also

bind(), socket(), getpeername().


4.1.7 getsockopt()

Description

Retrieve a socket option.

#include <winsock.h>

int PASCAL FAR getsockopt ( SOCKET s, int level, int optname, char FAR * optval, int FAR * optlen );


s

A descriptor identifying a socket.

level

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

optname

The socket option for which the value is to be retrieved.

optval

A pointer to the buffer in which the value for the requested option is to be returned.

optlen

A pointer to the size of the optval buffer.


Remarks

getsockopt() retrieves the current value for a socket option associated with a socket of any type, in any state, and stores the result in optval. Options may exist at multiple protocol levels, but they are always present at the uppermost "socket'' level. Options affect socket operations, such as whether an operation blocks or not, the routing of packets, out-of-band data transfer, etc.


The value associated with the selected option is returned in the buffer optval. The integer pointed to by optlen should originally contain the size of this buffer; on return, it will be set to the size of the value returned. For SO_LINGER, this will be the size of a struct linger; for all other options it will be the size of an integer.

If the option was never set with setsockopt(), then getsockopt() returns the default value for the option.

The following options are supported for getsockopt(). The Type identifies the type of data addressed by optval. The TCP_NODELAY option uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Value

Type

Meaning


SO_ACCEPTCONN

BOOL

Socket is listen()ing.

SO_BROADCAST

BOOL

Socket is configured for the transmission of broadcast messages.

SO_DEBUG

BOOL

Debugging is enabled.

SO_DONTLINGER

BOOL

If true, the SO_LINGER option is disabled.

SO_DONTROUTE

BOOL

Routing is disabled.

SO_ERROR

int

Retrieve error status and clear.

SO_KEEPALIVE

BOOL

Keepalives are being sent.

SO_LINGER

struct linger FAR *

Returns the current linger options.

SO_OOBINLINE

BOOL

Out-of-band data is being received in the normal data stream.

SO_RCVBUF

int

Buffer size for receives

SO_REUSEADDR

BOOL

The socket may be bound to an address which is already in use.

SO_SNDBUF

int

Buffer size for sends

SO_TYPE

int

The type of the socket (e.g. SOCK_STREAM).

TCP_NODELAY

BOOL

Disables the Nagle algorithm for send coalescing.


BSD options not supported for getsockopt() are:

Value

Type

Meaning


SO_RCVLOWAT

int

Receive low water mark

SO_RCVTIMEO

int

Receive timeout

SO_SNDLOWAT

int

Send low water mark

SO_SNDTIMEO

int

Send timeout

IP_OPTIONS

Get options in IP header.

TCP_MAXSEG

int

Get TCP maximum segment size.


Calling getsockopt() with an unsupported option will result in an error code of WSAENOPROTOOPT being returned from WSAGetLastError().

Return Value

If no error occurs, getsockopt() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT
WSAEINPROGRESS

WSAENOPROTOOPT






WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The optlen argument was invalid.
A blocking Windows Sockets operation is in progress.
The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_ACCEPTCONN, SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.
The descriptor is not a socket.


See Also

setsockopt(), WSAAsyncSelect(), socket().


4.1.8 htonl()

Description

Convert a u_long from host to network byte order.

#include <winsock.h>

u_long PASCAL FAR htonl ( u_long hostlong );


hostlong

A 32-bit number in host byte order.


Remarks

This routine takes a 32-bit number in host byte order and returns a 32-bit number in network byte order.

Return Value

htonl() returns the value in network byte order.

See Also

htons(), ntohl(), ntohs().


4.1.9 htons()

Description

Convert a u_short from host to network byte order.

#include <winsock.h>

u_short PASCAL FAR htons ( u_short hostshort );


hostshort

A 16-bit number in host byte order.


Remarks

This routine takes a 16-bit number in host byte order and returns a 16-bit number in network byte order.

Return Value

htons() returns the value in network byte order.

See Also

htonl(), ntohl(), ntohs().


4.1.10 inet_addr()

Description

Convert a string containing a dotted address into an in_addr.

#include <winsock.h>

unsigned long PASCAL FAR inet_addr ( const char FAR * cp );


cp

A character string representing a number expressed in the Internet standard ".'' notation.


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

When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right most two bytes of the network address. This makes the three part address format convenient for specifying Class B network addresses as "128.net.host''.

When a two part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right most three bytes of the network address. This makes the two part address format convenient for specifying Class A network addresses as "net.host''.

When only one part is given, the value is stored directly in the network address without any byte rearrangement.

Return Value

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()


4.1.11 inet_ntoa()

Description

Convert a network address into a string in dotted format.

#include <winsock.h>

char FAR * PASCAL FAR inet_ntoa ( struct in_addr in );


in

A structure which represents an Internet host address.


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 the Windows Sockets implementation. 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 API call within the same thread, but no longer.

Return Value

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().


4.1.12 ioctlsocket()

Description

Control the mode of a socket.

#include <winsock.h>

int PASCAL FAR ioctlsocket ( SOCKET s, long cmd, u_long FAR * argp );


s

A descriptor identifying a socket.

cmd

The command to perform on the socket s.

argp

A pointer to a parameter for cmd.


Remarks

This routine may be used on any socket in any state. It is used to get or retrieve operating parameters associated with the socket, independent of the protocol and communications subsystem. The following commands are supported:


Command

Semantics

FIONBIO

Enable or disable non-blocking mode on the socket s. argp points at an unsigned long, which is non-zero if non-blocking mode is to be enabled and zero if it is to be disabled. When a socket is created, it operates in blocking mode (i.e. non-blocking mode is disabled). This is consistent with BSD sockets.
The WSAAsyncSelect() routine automatically sets a socket to nonblocking mode. If WSAAsyncSelect() has been issued on a socket, then any attempt to use ioctlsocket() to set the socket back to blocking mode will fail with WSAEINVAL. To set the socket back to blocking mode, an application must first disable WSAAsyncSelect() by calling WSAAsyncSelect() with the lEvent parameter equal to 0.

FIONREAD

Determine the amount of data which can be read atomically from socket s. argp points at an unsigned long in which ioctlsocket() stores the result. If s is of type SOCK_STREAM, FIONREAD returns the total amount of data which may be read in a single recv(); this is normally the same as the total amount of data queued on the socket. If s is of type SOCK_DGRAM, FIONREAD returns the size of the first datagram queued on the socket.

SIOCATMARK

Determine whether or not all out-of-band data has been read. This applies only to a socket of type SOCK_STREAM which has been configured for in-line reception of any out-of-band data (SO_OOBINLINE). If no out-of-band data is waiting to be read, the operation returns TRUE. Otherwise it returns FALSE, and the next recv() or recvfrom() performed on the socket will retrieve some or all of the data preceding the "mark"; the application should use the SIOCATMARK operation to determine whether any remains. If there is any normal data preceding the "urgent" (out of band) data, it will be received in order. (Note that a recv() or recvfrom() will never mix out-of-band and normal data in the same call.) argp points at a BOOL in which ioctlsocket() stores the result.


Compatibility

This function is a subset of ioctl() as used in Berkeley sockets. In particular, there is no command which is equivalent to FIOASYNC, while SIOCATMARK is the only socket-level command which is supported.

Return Value

Upon successful completion, the ioctlsocket() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEINVAL


WSAEINPROGRESS

WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
cmd is not a valid command, or argp is not an acceptable parameter for cmd, or the command is not applicable to the type of socket supplied
A blocking Windows Sockets operation is in progress.


See Also

socket(), setsockopt(), getsockopt(), WSAAsyncSelect().


4.1.13 listen()

Description

Establish a socket to listen for incoming connection.

#include <winsock.h>

int PASCAL FAR listen ( SOCKET s, int backlog );


s

A descriptor identifying a bound, unconnected socket.

backlog

The maximum length to which the queue of pending connections may grow.


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 support connections, i.e. those of type SOCK_STREAM. The socket s is put into "passive'' mode where incoming connections 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 re-fill the queue to the current or most recent "backlog'', if possible, and resume listening for incoming connections.

Compatibility

backlog is currently limited (silently) to 5. As in 4.3BSD, illegal values (less than 1 or greater than 5) are replaced by the nearest legal value.

Return Value

If no error occurs, listen() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEADDRINUSE

WSAEINPROGRESS

WSAEINVAL

WSAEISCONN
WSAEMFILE
WSAENOBUFS
WSAENOTSOCK
WSAEOPNOTSUPP

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
An attempt has been made to listen() on an address in use.
A blocking Windows Sockets operation is in progress.
The socket has not been bound with bind() or is already connected.
The socket is already connected.
No more file descriptors are available.
No buffer space is available.
The descriptor is not a socket.
The referenced socket is not of a type that supports the listen() operation.


See Also

accept(), connect(), socket().


4.1.14 ntohl()

Description

Convert a u_long from network to host byte order.

#include <winsock.h>

u_long PASCAL FAR ntohl ( u_long netlong );


netlong

A 32-bit number in network byte order.


Remarks

This routine takes a 32-bit number in network byte order and returns a 32-bit number in host byte order.

Return Value

ntohl() returns the value in host byte order.

See Also

htonl(), htons(), ntohs().


4.1.15 ntohs()

Description

Convert a u_short from network to host byte order.

#include <winsock.h>

u_short PASCAL FAR ntohs ( u_short netshort );


netshort

A 16-bit number in network byte order.


Remarks

This routine takes a 16-bit number in network byte order and returns a 16-bit number in host byte order.

Return Value

ntohs() returns the value in host byte order.

See Also

htonl(), htons(), ntohl().


4.1.16 recv()

Description

Receive data from a socket.

#include <winsock.h>

int PASCAL FAR recv ( SOCKET s, char FAR * buf, int len, int flags );


s

A descriptor identifying a connected socket.

buf

A buffer for the incoming data.

len

The length of buf.

flags

Specifies the way in which the call is made.


Remarks

This function is used on connected datagram or stream sockets specified by the s parameter and is used to read incoming data.

For sockets 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 may use the ioctlsocket() SIOCATMARK to determine whether any more out-of-band data remains to be read.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the datagram, the excess data is lost, and recv() returns the error WSAEMSGSIZE.

If no incoming data is available at the socket, the recv() call waits for data to arrive unless the socket is non-blocking. In this case a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select() or WSAAsyncSelect() calls may be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a recv() will complete immediately with 0 bytes received. If the connection has been reset, a recv() will fail with the error WSAECONNRESET.

Flags may 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 2.2.3 for a discussion of this topic.)


Return Value

If no error occurs, recv() returns the number of bytes received. If the connection has been closed, it returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAENOTCONN
WSAEINTR

WSAEINPROGRESS

WSAENOTSOCK
WSAEOPNOTSUPP

WSAESHUTDOWN


WSAEWOULDBLOCK

WSAEMSGSIZE

WSAEINVAL
WSAECONNABORTED

WSAECONNRESET

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The socket is not connected.
The (blocking) call was canceled via WSACancelBlockingCall().
A blocking Windows Sockets operation is in progress.
The descriptor is not a socket.
MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
The socket has been shutdown; it is not possible to recv() on a socket after shutdown() has been invoked with how set to 0 or 2.
The socket is marked as non-blocking and the receive operation would block.
The datagram was too large to fit into the specified buffer and was truncated.
The socket has not been bound with bind().
The virtual circuit was aborted due to timeout or other failure.
The virtual circuit was reset by the remote side.


See Also

recvfrom(), \deleted read(), ,recv(), send(), select(), WSAAsyncSelect(), socket()


4.1.17 recvfrom()

Description

Receive a datagram and store the source address.

#include <winsock.h>

int PASCAL FAR recvfrom ( SOCKET s, char FAR * buf, int len, int flags,

struct sockaddr FAR * from, int FAR * fromlen );


s

A descriptor identifying a bound socket.

buf

A buffer for the incoming data.

len

The length of buf.

flags

Specifies the way in which the call is made.

from

An optional pointer to a buffer which will hold the source address upon return.

fromlen

An optional pointer to the size of the from buffer.


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 sockets 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 may 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 SOCK_STREAM sockets.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the message, the excess data is lost, and recvfrom() returns the error code WSAEMSGSIZE.

If from is non-zero, and the socket is of 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 non-blocking. In this case a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select() or WSAAsyncSelect() calls may be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a recvfrom() will complete immediately with 0 bytes received. If the connection has been reset recv() will fail with the error WSAECONNRESET.

Flags may 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 2.2.3 for a discussion of this topic.)

Return Value

If no error occurs, recvfrom() returns the number of bytes received. If the connection has been closed, it returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT


WSAEINTR

WSAEINPROGRESS

WSAEINVAL
WSAENOTCONN

WSAENOTSOCK
WSAEOPNOTSUPP

WSAESHUTDOWN


WSAEWOULDBLOCK

WSAEMSGSIZE

WSAECONNABORTED

WSAECONNRESET

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The fromlen argument was invalid: the from buffer was too small to accommodate the peer address.
The (blocking) call was canceled via WSACancelBlockingCall().
A blocking Windows Sockets operation is in progress.
The socket has not been bound with bind().
The socket is not connected (SOCK_STREAM only).
The descriptor is not a socket.
MSG_OOB was specified, but the socket is not of type SOCK_STREAM.
The socket has been shutdown; it is not possible to recvfrom() on a socket after shutdown() has been invoked with how set to 0 or 2.
The socket is marked as non-blocking and the recvfrom() operation would block.
The datagram was too large to fit into the specified buffer and was truncated.
The virtual circuit was aborted due to timeout or other failure.
The virtual circuit was reset by the remote side.


See Also

recv(), send(), socket(), WSAAsyncSelect().


4.1.18 select()

Description

Determine the status of one or more sockets, waiting if necessary.

#include <winsock.h>

int PASCAL FAR select ( int nfds, fd_set FAR * readfds, fd_set FAR * writefds, fd_set FAR * exceptfds, const struct timeval FAR * timeout );


nfds

This argument is ignored and included only for the sake of compatibility.

readfds

An optional pointer to a set of sockets to be checked for readability.

writefds

An optional pointer to a set of sockets to be checked for writability

exceptfds

An optional pointer to a set of sockets to be checked for errors.

timeout

The maximum time for select() to wait, or NULL for blocking operation.


Remarks

This function is used to determine the status of one or more sockets. For each socket, the caller may request information on read, write or error status. The set of sockets for which a given status is requested is indicated by an fd_set structure. Upon return, the structure is updated to reflect the subset of these sockets which meet the specified condition, and select() returns the number of sockets meeting the conditions. A set of macros is provided for manipulating an fd_set. These macros are compatible with those used in the Berkeley software, but the underlying representation is completely different.

The parameter readfds identifies those sockets which are to be checked for readability. If the socket is currently listen()ing, it will be marked as readable if an incoming connection request has been received, so that an accept() is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading or, for sockets of type SOCK_STREAM, that the virtual socket corresponding to the socket has been closed, so that a recv() or recvfrom() is guaranteed to complete without blocking. If the virtual circuit was closed gracefully, then a recv() will return immediately with 0 bytes read; if the virtual circuit was reset, then a recv() will complete immediately with the error code WSAECONNRESET. The presence of out-of-band data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt()).

The parameter writefds identifies those sockets which are to be checked for writability. If a socket is connect()ing (non-blocking), writability means that the connection establishment successfully completed. If the socket is not in the process of connect()ing, writability means that a send() or sendto() will complete without blocking. [It is not specified how long this guarantee can be assumed to be valid, particularly in a multithreaded environment.]

The parameter exceptfds identifies those sockets which are to be checked for the presence of out-of-band data or any exceptional error conditions. Note that out-of-band data will only be reported in this way if the option SO_OOBINLINE is FALSE. For a SOCK_STREAM, the breaking of the connection by the peer or due to KEEPALIVE failure will be indicated as an exception. This specification does not define which other errors will be included. If a socket is connect()ing (non-blocking), failure of the connect attempt is indicated in exceptfds.

Any of readfds, writefds, or exceptfds may be given as NULL if no descriptors are of interest.

Four macros are defined in the header file winsock.h for manipulating the descriptor sets. The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which may be modified by #defining FD_SETSIZE to another value before #including winsock.h.) Internally, an fd_set is represented as an array of SOCKETs; the last valid entry is followed by an element set to INVALID_SOCKET. The macros are:

FD_CLR(s, *set) Removes the descriptor s from set.
FD_ISSET(s, *set) Nonzero if s is a member of the set, zero otherwise.
FD_SET(s, *set) Adds descriptor s to set.
FD_ZERO(*set) Initializes the set to the NULL set.

The parameter timeout controls how long the select() may take to complete. If timeout is a null pointer, select() will block indefinitely until at least one descriptor meets the specified criteria. Otherwise, timeout points to a struct timeval which specifies the maximum time that select() should wait before returning. If the timeval is initialized to {0, 0}, select() will return immediately; this is used to "poll" the state of the selected sockets. If this is the case, then the select() call is considered nonblocking and the standard assumptions for nonblocking calls apply. For example, the blocking hook must not be called, and the Windows Sockets implementation must not yield.

Return Value

select() returns the total number of descriptors which are ready and contained in the fd_set structures, 0 if the time limit expired, or SOCKET_ERROR if an error occurred. If the return value is SOCKET_ERROR, WSAGetLastError() may be used to retrieve a specific error code.


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEINVAL
WSAEINTR

WSAEINPROGRESS

WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The timeout value is not valid.
The (blocking) call was canceled via WSACancelBlockingCall().
A blocking Windows Sockets operation is in progress.
One of the descriptor sets contains an entry which is not a socket.


See Also

WSAAsyncSelect(), accept(), connect(), recv(), recvfrom(), send().


4.1.19 send()

Description

Send data on a connected socket.

#include <winsock.h>

int PASCAL FAR send ( SOCKET s, const char FAR * buf, int len, int flags );


s

A descriptor identifying a connected socket.

buf

A buffer containing the data to be transmitted.

len

The length of the data in buf.

flags

Specifies the way in which the call is made.


Remarks

send() is used on connected datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup(). If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.


Note that the successful completion of a send() does not indicate that the data was successfully delivered.

If no buffer space is available within the transport system to hold the data to be transmitted, send() will block unless the socket has been placed in a non-blocking I/O mode. On non-blocking SOCK_STREAM sockets, the number of bytes written may be between 1 and the requested length, depending on buffer availability on both the local and foreign hosts. The select() call may be used to determine when it is possible to send more data.

Flags may 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 supplier may choose to ignore this flag; see also the discussion of the SO_DONTROUTE option in section 2.4.

MSG_OOB

Send out-of-band data (SOCK_STREAM only; see also section 2.2.3)

Return Value

If no error occurs, send() returns the total number of characters sent. (Note that this may be less than the number indicated by len.) Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

A successful WSAStartup() must occur before using this API.

WSAENETDOWN

The Windows Sockets implementation has detected that the network subsystem has failed.

WSAEACCES

The requested address is a broadcast address, but the appropriate flag was not set.

WSAEINTR

The (blocking) call was canceled via WSACancelBlockingCall().

WSAEINPROGRESS

A blocking Windows Sockets operation is in progress.

WSAEFAULT

The buf argument is not in a valid part of the user address space.

WSAENETRESET

The connection must be reset because the Windows Sockets implementation dropped it.

WSAENOBUFS

The Windows Sockets implementation reports a buffer deadlock.

WSAENOTCONN

The socket is not connected.

WSAENOTSOCK

The descriptor is not a socket.

WSAEOPNOTSUPP

MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

WSAESHUTDOWN

The socket has been shutdown; it is not possible to send() on a socket after shutdown() has been invoked with how set to 1 or 2.

WSAEWOULDBLOCK

The socket is marked as non-blocking and the requested operation would block.

WSAEMSGSIZE

The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.

WSAEINVAL

The socket has not been bound with bind().

WSAECONNABORTED

The virtual circuit was aborted due to timeout or other failure.

WSAECONNRESET

The virtual circuit was reset by the remote side.


See Also

recv(), recvfrom(), socket(), sendto(), WSAStartup().


4.1.20 sendto()

Description

Send data to a specific destination.

#include <winsock.h>

int PASCAL FAR sendto ( SOCKET s, const char FAR * buf, int len, int flags, const struct sockaddr FAR * to, int tolen );


s

A descriptor identifying a socket.

buf

A buffer containing the data to be transmitted.

len

The length of the data in buf.

flags

Specifies the way in which the call is made.

to

An optional pointer to the address of the target socket.

tolen

The size of the address in to.


Remarks

sendto() is used on datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSAData structure returned by WSAStartup(). If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.


Note that the successful completion of a sendto() does not indicate that the data was successfully delivered.

sendto() is normally used on a SOCK_DGRAM socket to send a datagram to a specific peer socket identified by the to parameter. On a SOCK_STREAM socket, the to and tolen parameters are ignored; in this case the sendto() is equivalent to send().

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 winsock.h) together with the intended port number. It is generally inadvisable for a broadcast datagram to exceed the size at which fragmentation may 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 non-blocking I/O mode. On non-blocking SOCK_STREAM sockets, the number of bytes written may be between 1 and the requested length, depending on buffer availability on both the local and foreign hosts. The select() call may be used to determine when it is possible to send more data.

Flags may 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 supplier may choose to ignore this flag; see also the discussion of the SO_DONTROUTE option in section .

MSG_OOB

Send out-of-band data (SOCK_STREAM only; see also section )

Return Value

If no error occurs, sendto() returns the total number of characters sent. (Note that this may be less than the number indicated by len.) Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN


WSAEACCES

WSAEINTR

WSAEINPROGRESS

WSAEFAULT


WSAENETRESET

WSAENOBUFS

WSAENOTCONN

WSAENOTSOCK
WSAEOPNOTSUPP

WSAESHUTDOWN



WSAEWOULDBLOCK

WSAEMSGSIZE



WSAECONNABORTED

WSAECONNRESET

WSAEADDRNOTAVAIL

WSAEAFNOSUPPORT

WSAEDESTADDRREQ
WSAENETUNREACH

A successful WSAStartup() must occur before using this API.

The Windows Sockets implementation has detected that the network subsystem has failed.

The requested address is a broadcast address, but the appropriate flag was not set.

The (blocking) call was canceled via WSACancelBlockingCall().

A blocking Windows Sockets operation is in progress.

The buf or to parameters are not part of the user address space, or the to argument is too small (less than the sizeof a struct sockaddr).

The connection must be reset because the Windows Sockets implementation dropped it.

The Windows Sockets implementation reports a buffer deadlock.

The socket is not connected (SOCK_STREAM only).

The descriptor is not a socket.

MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

The socket has been shutdown; it is not possible to sendto() on a socket after shutdown() has been invoked with how set to 1 or 2.

The socket is marked as non-blocking and the requested operation would block.

The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.

The virtual circuit was aborted due to timeout or other failure.

The virtual circuit was reset by the remote side.

The specified address is not available from the local machine.\deleted

Addresses in the specified family cannot be used with this socket.

A destination address is required.

The network can't be reached from this host at this time.


See Also

recv(), recvfrom(), socket(), send(), WSAStartup().


4.1.21 setsockopt()

Description

Set a socket option.

#include <winsock.h>

int PASCAL FAR setsockopt ( SOCKET s, int level, int optname, const char FAR * optval, int optlen );


s

A descriptor identifying a socket.

level

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

optname

The socket option for which the value is to be set.

optval

A pointer to the buffer in which the value for the requested option is supplied.

optlen

The size of the optval buffer.


Remarks

setsockopt() sets the current value for a socket option associated with a socket of any type, in any state. Although options may exist at multiple protocol levels, this specification only defines options that exist at the uppermost "socket'' level. Options affect socket operations, such as whether expedited data is received in the normal data stream, whether broadcast messages may be sent on the socket, etc.


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.

SO_LINGER controls the action taken when unsent data is queued on a socket and a closesocket() is performed. See closesocket() for a description of the way in which the SO_LINGER settings affect the semantics of closesocket(). The application sets the desired behavior by creating a struct linger (pointed to by the optval argument) with the following elements:


struct linger {
    int    l_onoff;
    int    l_linger;
}

To enable SO_LINGER, the application should set l_onoff to a non-zero value, set l_linger to 0 or the desired timeout (in seconds), and call setsockopt(). To enable SO_DONTLINGER (i.e. disable SO_LINGER) l_onoff should be set to zero and setsockopt() should be called.

By default, a socket may not be bound (see bind()) to a local address which is already in use. On occasions, however, it may be desirable to "re-use" an address in this way. Since every connection is uniquely identified by the combination of local and remote addresses, there is no problem with having two sockets bound to the same local address as long as the remote addresses are different. To inform the Windows Sockets implementation that a bind() on a socket should not be disallowed because the desired address is already in use by another socket, the application should set the SO_REUSEADDR socket option for the socket before issuing the bind(). Note that the option is interpreted only at the time of the bind(): it is therefore unnecessary (but harmless) to set the option on a socket which is not to be bound to an existing address, and setting or resetting the option after the bind() has no effect on this or any other socket.

An application may request that the Windows Sockets implementation enable the use of "keep-alive" packets on TCP connections by turning on the SO_KEEPALIVE socket option. A Windows Sockets implementation need not support the use of keep-alives: if it does, the precise semantics are implementation-specific but should conform to section 4.2.3.6 of RFC 1122: Requirements for Internet Hosts -- Communication Layers. If a connection is dropped as the result of "keep-alives" the error code WSAENETRESET is returned to any calls in progress on the socket, and any subsequent calls will fail with WSAENOTCONN.

The TCP_NODELAY option disables the Nagle algorithm. The Nagle algorithm is used to reduce the number of small packets sent by a host by buffering unacknowledged send data until a full-size packet can be sent. However, for some applications this algorithm can impede performance, and TCP_NODELAY may be used to turn it off. Application writers should not set TCP_NODELAY unless the impact of doing so is well-understood and desired, since setting TCP_NODELAY can have a significant negative impact of network performance. TCP_NODELAY is the only supported socket option which uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Windows Sockets suppliers are encouraged (but not required) to supply output debug information if the SO_DEBUG option is set by an application. The mechanism for generating the debug information and the form it takes are beyond the scope of this specification.

The following options are supported for setsockopt(). The Type identifies the type of data addressed by optval.

Value

Type

Meaning


SO_BROADCAST

BOOL

Allow transmission of broadcast messages on the socket.

SO_DEBUG

BOOL

Record debugging information.

SO_DONTLINGER

BOOL

Don't 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

Don't route: send directly to interface.

SO_KEEPALIVE

BOOL

Send keepalives

SO_LINGER

struct linger FAR *

Linger on close if unsent data is present

SO_OOBINLINE

BOOL

Receive out-of-band data in the normal data stream.

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.

TCP_NODELAY

BOOL

Disables the Nagle algorithm for send coalescing.


BSD options not supported for setsockopt() are:

Value

Type

Meaning


SO_ACCEPTCONN

BOOL

Socket is listening

SO_ERROR

int

Get error status and clear

SO_RCVLOWAT

int

Receive low water mark

SO_RCVTIMEO

int

Receive timeout

SO_SNDLOWAT

int

Send low water mark

SO_SNDTIMEO

int

Send timeout

SO_TYPE

int

Type of the socket

IP_OPTIONS

Set options field in IP header.


Return Value

If no error occurs, setsockopt() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEFAULT

WSAEINPROGRESS

WSAEINVAL

WSAENETRESET

WSAENOPROTOOPT





WSAENOTCONN

WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
optval is not in a valid part of the process address space.
A blocking Windows Sockets operation is in progress.
level is not valid, or the information in optval is not valid.
Connection has timed out when SO_KEEPALIVE is set.
The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.
Connection has been reset when SO_KEEPALIVE is set.
The descriptor is not a socket.


See Also

bind(), getsockopt(), ioctlsocket(), socket(), WSAAsyncSelect().


4.1.22 shutdown()

Description

Disable sends and/or receives on a socket.

#include <winsock.h>

int PASCAL FAR shutdown ( SOCKET s, int how );


s

A descriptor identifying a socket.

how

A flag that describes what types of operation will no longer be allowed.


Remarks

shutdown() is used on all types of sockets to disable reception, transmission, or both.
If how is 0, subsequent receives on the socket will be disallowed. This has no effect on the lower protocol layers. For TCP, the TCP window is not changed and incoming data will be accepted (but not acknowledged) until the window is exhausted. For UDP, incoming datagrams are accepted and queued. In no case will an ICMP error packet be generated.
If how is 1, subsequent sends are disallowed. For TCP sockets, a FIN will be sent.
Setting how to 2 disables both sends and receives as described above.
Note that shutdown() does not close the socket, and resources attached to the socket will not be freed until closesocket() is invoked.

Comments

shutdown() does not block regardless of the SO_LINGER setting on the socket.
An application should not rely on being able to re-use a socket after it has been shut down. In particular, a Windows Sockets implementation is not required to support the use of connect() on such a socket.

Return Value

If no error occurs, shutdown() returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEINVAL
WSAEINPROGRESS

WSAENOTCONN

WSAENOTSOCK

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
how is not valid.
A blocking Windows Sockets operation is in progress.
The socket is not connected (SOCK_STREAM only).
The descriptor is not a socket.


See Also

connect(), socket().


4.1.23 socket()

Description

Create a socket.

#include <winsock.h>

SOCKET PASCAL FAR socket ( int af, int type, int protocol );


af

An address format specification. The only format currently supported is PF_INET, which is the ARPA Internet address format.

type

A type specification for the new socket.

protocol

A particular protocol to be used with the socket, or 0 if the caller does not wish to specify a protocol.


Remarks

socket() allocates a socket descriptor of the specified address family, data type and protocol, as well as related resources. If a protocol is not specified (i.e. equal to 0), the default for the specified connection mode is used. Only a single protocol exists to support a particular socket type using a given address format. However, the address family may be given as AF_UNSPEC (unspecified), in which case the protocol parameter must be specified. The protocol number to use is particular to the "communication domain'' in which communication is to take place.The following type specifications are supported:


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.


Sockets of type SOCK_STREAM are full-duplex byte streams. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect() call. Once connected, data may be transferred using send() and recv() calls. When a session has been completed, a closesocket() must be performed. Out-of-band data may also be transmitted as described in send() and received as described in recv().

The communications protocols used to implement a SOCK_STREAM ensure that data is not lost or duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT.

SOCK_DGRAM sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto() and recvfrom(). If such a socket is connect()ed to a specific peer, datagrams may be send to that peer send() and may be received from (only) this peer using recv().


Return Value

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 may be retrieved by calling WSAGetLastError().


Error Codes

WSANOTINITIALISED

WSAENETDOWN

WSAEAFNOSUPPORT
WSAEINPROGRESS

WSAEMFILE
WSAENOBUFS

WSAEPROTONOSUPPORT


WSAEPROTOTYPE

WSAESOCKTNOSUPPORT

A successful WSAStartup() must occur before using this API.
The Windows Sockets implementation has detected that the network subsystem has failed.
The specified address family is not supported.
A blocking Windows Sockets operation is in progress.
No more file descriptors are available.
No buffer space is available. The socket cannot be created.
The specified protocol is not supported.
The specified protocol is the wrong type for this socket.
The specified socket type is not supported in this address family.


See Also

accept(), bind(), connect(), getsockname(), getsockopt(), setsockopt(), listen(), recv(), recvfrom(), select(), send(), sendto(), shutdown(), ioctlsocket().