Unit OS A: Windows Networking Unit OS A: Windows Networking
A.2. A.2. Windows Sockets Programming Windows Sockets Programming
Copyright Notice Copyright Notice
© 2000-2005 David A. Solomon and Mark Russinovich
© 2000-2005 David A. Solomon and Mark Russinovich
These materials are part of the
These materials are part of the Windows Operating Windows Operating System Internals Curriculum Development Kit,
System Internals Curriculum Development Kit, developed by David A. Solomon and Mark E.
developed by David A. Solomon and Mark E.
Russinovich with Andreas Polze Russinovich with Andreas Polze
Microsoft has licensed these materials from David Microsoft has licensed these materials from David Solomon Expert Seminars, Inc. for distribution to Solomon Expert Seminars, Inc. for distribution to academic organizations solely for use in academic academic organizations solely for use in academic environments (and not for commercial use)
environments (and not for commercial use)
Roadmap for Section A.2 Roadmap for Section A.2
General Concepts - Berkeley Sockets General Concepts - Berkeley Sockets
Creating a socket Creating a socket
Binding an address Binding an address
Accepting connections Accepting connections
Exchanging data Exchanging data
Closing a connection Closing a connection
Managing multiple connections with select()
Managing multiple connections with select()
Winsock Features Winsock Features
Support for scatter-gather and asynchronous application I/O Support for scatter-gather and asynchronous application I/O Quality of service (QoS) conventions so that applications can Quality of service (QoS) conventions so that applications can
negotiate latency and bandwidth requirements when the underlying negotiate latency and bandwidth requirements when the underlying network supports QoS
network supports QoS
Extensibility so that Winsock can be used with protocols other than Extensibility so that Winsock can be used with protocols other than those Windows requires it to support
those Windows requires it to support
Support for integrated namespaces other than those defined by a Support for integrated namespaces other than those defined by a protocol an application is using with Winsock. A server can publish protocol an application is using with Winsock. A server can publish its name in Active Directory, for example, and using namespace its name in Active Directory, for example, and using namespace extensions, a client can look up the server's address in Active extensions, a client can look up the server's address in Active Directory
Directory
Support for multipoint messages where messages transmit to Support for multipoint messages where messages transmit to multiple receivers simultaneously
multiple receivers simultaneously
Windows Socket Programming Windows Socket Programming
Berkeley Socket programs will port to Window Sockets Berkeley Socket programs will port to Window Sockets Exceptions:
Exceptions:
Call
Call WSAStartup()WSAStartup() to initialize Windows Socket DLL to initialize Windows Socket DLL Use ioctlsocket()Use ioctlsocket() (non-portable) to configure the socket (non-portable) to configure the socket _read()
_read() and and _write()_write() can be used on sockets, but only after can be used on sockets, but only after converting the socket descriptor to a file handle via
converting the socket descriptor to a file handle via _open_osfhandle()
_open_osfhandle()
Use Use closesocket()closesocket() (non-portable) rather than close to close a (non-portable) rather than close to close a socket
socket Call
Call WSACleanup()WSACleanup() to shut down the DLL to shut down the DLL
Berkeley
Berkeley 4.3 4.3 UNIX Sockets UNIX Sockets – – connection-oriented
connection-oriented
Server
socket()
bind()
listen()
accept()
read() write()
socket()
Client
connect()
write() read() connection establishment
data (request) data (reply) blocks until connection
from client
Berkeley 4.3 UNIX Sockets - Berkeley 4.3 UNIX Sockets -
connectionless connectionless
Server
socket() bind() recvfrom()
sendto()
socket()
Client
sendto()
recvfrom() data (request)
data (reply) blocks until data
received from client
Unix SYS V.3 Transport Layer Unix SYS V.3 Transport Layer Interface – connection-oriented Interface – connection-oriented
Server t_open()
t_bind()
t_listen()
t_rcv() t_snd()
t_open()
Client
t_connect()
t_snd() t_rcv() data (request)
data (reply) blocks until connection
from client
t_alloc() t_bind()
t_alloc()
t_accept()
connection establishment
Unix SYS V.3 Transport Layer Unix SYS V.3 Transport Layer
Interface
Interface - - connectionless connectionless
Server
t_open() t_bind()
t_rcvudata()
t_sndudata()
t_open()
Client
t_sndudata()
t_rcvudata() data (request)
data (reply) blocks until data
received from client
t_alloc() t_bind()
t_alloc()
Create a socket Create a socket
af af : An address format specification. The only format : An address format specification. The only format currently supported is AF_INET, which is the ARPA currently supported is AF_INET, which is the ARPA Internet address format.
Internet address format.
type: A type specification for the new socket. type : A type specification for the new socket.
protocol
protocol : A particular protocol to be used with the : A particular protocol to be used with the socket, or 0 if the caller does not wish to specify a socket, or 0 if the caller does not wish to specify a protocol.
protocol.
#include <winsock.h>
SOCKET socket (
int af, int type, int protocol );
Accept a connection on a socket Accept a connection on a socket
s: A descriptor identifying a socket which is listening for s: A descriptor identifying a socket which is listening for connections after a listen().
connections after a listen().
addr:
addr: An optional pointer to a buffer which receives the address of An optional pointer to a buffer which receives the address of the connecting entity, as known to the communications layer. The the connecting entity, as known to the communications layer. The
exact format of the addr argument is determined by the address exact format of the addr argument is determined by the address
family established when the socket was created.
family established when the socket was created.
addrlen:
addrlen: An optional pointer to an integer which contains the length An optional pointer to an integer which contains the length of the address addr.
of the address addr.
#include <winsock.h>
SOCKET accept (
SOCKET s, struct sockaddr FAR * addr, int FAR * addrlen );
struct sockaddr struct sockaddr
From winsock.h (Windows) or From winsock.h (Windows) or
/usr/include/sys/socket.h (UNIX) /usr/include/sys/socket.h (UNIX)
/*
* Structure used by kernel to store most * addresses.
*/
struct sockaddr {
u_char sa_len; /* total length */
u_char sa_family; /* address family */
char sa_data[14]; /* actually longer; address value*/
};
#define SOCK_MAXADDRLEN 255 /* longest possible addresses */
Associate a local address Associate a local address
with a socket with a socket
s: A descriptor identifying an unbound socket. s: A descriptor identifying an unbound socket.
name:
name: The address to assign to the socket. The address to assign to the socket.
namelen
namelen: length of the name : length of the name
struct sockaddr { struct sockaddr {
u_short sa_family;
u_short sa_family;
char sa_data[14];
char sa_data[14];
};};
#include <winsock.h>
int bind (
SOCKET s, const struct sockaddr FAR * name, int namelen );
Internet address family Internet address family
In the Internet address family, a name consists of several In the Internet address family, a name consists of several components.
components.
For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts:
For SOCK_DGRAM and SOCK_STREAM, the name consists of three parts:
a host address, the protocol number (set implicitly to UDP or TCP, a host address, the protocol number (set implicitly to UDP or TCP, respectively), and a port number which identifies the application.
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 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.
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 If the Internet address is equal to INADDR_ANY, any appropriate network interface will be used; this simplifies application programming in the presence interface will be used; this simplifies application programming in the presence of multi-homed hosts.
of multi-homed hosts.
If the port is specified as 0, the Windows Sockets implementation will assign a 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.
unique port to the application with a value between 1024 and 5000.
The application may use getsockname() after bind() to learn the address that The application may use getsockname() after bind() to learn the address that has been assigned to it
has been assigned to it
getsockname() will not necessarily fill in the Internet address until the socket is getsockname() will not necessarily fill in the Internet address until the socket is connected; several Internet addresses may be valid if the host is multi-homed.
connected; several Internet addresses may be valid if the host is multi-homed.
Example: bind to an reserved port Example: bind to an reserved port
SOCKADDR_IN sin;
SOCKADDR_IN sin;
SOCKET s;
SOCKET s;
u_short alport = IPPORT_RESERVED; /* 1024 */
u_short alport = IPPORT_RESERVED; /* 1024 */
sin.sin_family = AF_INET;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_addr.s_addr = 0;
for (;;) { for (;;) {
sin.sin_port = htons(alport);
sin.sin_port = htons(alport);
if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0) { if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0) { /* it worked */
/* it worked */
} }
if ( GetLastError() != WSAEADDRINUSE) { if ( GetLastError() != WSAEADDRINUSE) {
/* fail */
/* fail */
} }
alport--;
alport--;
if (alport == IPPORT_RESERVED/2 ) { if (alport == IPPORT_RESERVED/2 ) {
/* fail--all unassigned reserved ports are in use.*/
/* fail--all unassigned reserved ports are in use.*/
} } } }
Close a socket Close a socket
This function closes a socket.
This function closes a socket.
releases the socket descriptor s, so that further references to s will fail releases the socket descriptor s, so that further references to s will fail
with the error WSAENOTSOCK.
with the error WSAENOTSOCK.
If this is the last reference to the underlying socket, the associated If this is the last reference to the underlying socket, the associated
naming information and queued data are discarded.
naming information and queued data are discarded.
Semantics influenced by socket options:
Semantics influenced by socket options:
#include <winsock.h>
int closesocket ( SOCKET s );
Option
Option IntervalInterval Type of closeType of close Wait for close?Wait for close?
SO_DONTLINGER
SO_DONTLINGER Don‘t careDon‘t care GracefulGraceful NoNo SO_LINGER
SO_LINGER ZeroZero HardHard NoNo
SO_LINGER
SO_LINGER Non-zeroNon-zero GracefulGraceful YesYes
Establish a connection to a peer Establish a connection to a peer
ss: A descriptor identifying an unconnected socket. : A descriptor identifying an unconnected socket.
namename: The name of the peer to which the socket is to be connected. : The name of the peer to which the socket is to be connected.
namelen
namelen: The length of the name. : The length of the name.
create a connection to the specified foreign association. The create a connection to the specified foreign association. The
parameter s specifies an unconnected datagram or stream socket parameter s specifies an unconnected datagram or stream socket
#include <winsock.h>
int connect ( SOCKET s,
const struct sockaddr * name, int namelen );
Establish a socket to listen for Establish a socket to listen for
incoming connection incoming connection
s: A descriptor identifying a bound, unconnected socket. s: A descriptor identifying a bound, unconnected socket.
backlog
backlog: The maximum length to which the queue of pending connections : The maximum length to which the queue of pending connections may grow.
may grow.
typically used by servers that could have more than one connection request typically used by servers that could have more than one connection request at a time:
at a time:
if a connection request arrives with the queue full, the client will receive an if a connection request arrives with the queue full, the client will receive an error with an indication of WSAECONNREFUSED
error with an indication of WSAECONNREFUSED
#include <winsock.h>
int listen ( SOCKET s, int backlog );
Receiving data from a socket Receiving data from a socket
(connection-oriented) (connection-oriented)
s s : A descriptor identifying a connected socket. : A descriptor identifying a connected socket.
buf buf : A buffer for the incoming data. : A buffer for the incoming data.
len len : The length of buf. : The length of buf.
flags
flags: Specifies the way in which the call is made. : Specifies the way in which the call is made.
#include <winsock.h>
int recv ( SOCKET s,
char * buf, int len, int flags );
Receive a datagram and store the Receive a datagram and store the
source address
source address (connectionless) (connectionless)
s: A descriptor identifying a bound socket. s: A descriptor identifying a bound socket.
bufbuf: A buffer for the incoming data. : A buffer for the incoming data.
lenlen: The length of buf. : The length of buf.
flags
flags: Specifies the way in which the call is made. : Specifies the way in which the call is made.
from: An optional pointer to a buffer which will hold the source from: An optional pointer to a buffer which will hold the source address upon return.
address upon return.
fromlen
fromlen: An optional pointer to the size of the from buffer. : An optional pointer to the size of the from buffer.
#include <winsock.h>
int recvfrom ( SOCKET s,
char * buf, int len, int flags,
struct sockaddr * from, int * fromlen );
Determine the status of one or Determine the status of one or
more sockets, waiting if necessary.
more sockets, waiting if necessary.
nfds: nfds:
This argument is ignored and included only for the sake of compatibility.
This argument is ignored and included only for the sake of compatibility.
readfds readfds::
An optional pointer to a set of sockets to be checked for readability.
An optional pointer to a set of sockets to be checked for readability.
writefds writefds: :
An optional pointer to a set of sockets to be checked for writability An optional pointer to a set of sockets to be checked for writability exceptfds
exceptfds: :
An optional pointer to a set of sockets to be checked for errors.
An optional pointer to a set of sockets to be checked for errors.
timeout timeout: :
#include <winsock.h>
int select ( int nfds, fd_set * readfds,
fd_set * writefds, fd_set * exceptfds, const struct timeval * timeout );
Send data on a connected socket Send data on a connected socket
(connection-oriented) (connection-oriented)
ss: A descriptor identifying a connected socket. : A descriptor identifying a connected socket.
bufbuf: A buffer containing the data to be transmitted. : A buffer containing the data to be transmitted.
lenlen: The length of the data in buf. : The length of the data in buf.
flags
flags: Specifies the way in which the call is made.: Specifies the way in which the call is made.
#include <winsock.h>
int send ( SOCKET s,
const char * buf, int len, int flags );
Send data to a specific destination Send data to a specific destination
(connectionless) (connectionless)
ss: A descriptor identifying a socket. : A descriptor identifying a socket.
buf: A buffer containing the data to be transmitted. buf: A buffer containing the data to be transmitted.
lenlen: The length of the data in buf. : The length of the data in buf.
flags
flags: Specifies the way in which the call is made. : Specifies the way in which the call is made.
toto: An optional pointer to the address of the target socket. : An optional pointer to the address of the target socket.
tolen
tolen: The size of the address in to. : The size of the address in to.
#include <winsock.h>
int sendto ( SOCKET s,
const char * buf, int len, int flags, const struct sockaddr * to, int tolen );
Further Reading Further Reading
Mark E. Russinovich and David A. Solomon, Mark E. Russinovich and David A. Solomon,
Microsoft Windows Internals, 4th Edition, Microsoft Press, Microsoft Windows Internals, 4th Edition, Microsoft Press,
2004;
2004;
Windows Sockets (from pp. 791) Windows Sockets (from pp. 791)
Abraham Silberschatz, Peter B. Galvin, Operating System Abraham Silberschatz, Peter B. Galvin, Operating System
Concepts, John Wiley & Sons, 6th Ed., 2003;
Concepts, John Wiley & Sons, 6th Ed., 2003;
Chapter 15 - Distributed System Structures Chapter 15 - Distributed System Structures
W. Richard Stevens, Unix Network Programming, Prentice W. Richard Stevens, Unix Network Programming, Prentice
Hall Software Series, 1990; (
Hall Software Series, 1990; ( The Book The Book ) )
Chapter 6 - Berkeley Sockets Chapter 6 - Berkeley Sockets