Socket An end-point of a bidirectional process-to-process communication flow across an IP based network. Each socket is mapped to an application process or thread. A socket is an interface between an application process or thread and the TCP/IP protocol stack provided by the operating system. An Internet socket is identified by the operating system as a unique combination of the following: Protocol (TCP, UDP or raw IP) Local IP address Local port number Remote IP address Remote port number
Relevant Code WSAStartup(WORD VersionRequested, WSADATA *WSAData ) Generates the winsock environment according to the necessary revision. socket(int af, int type,int protocol) creates a new socket: Af – address family, normally AF_INET (IPv4). Type – socket type, normally SOCK_STREAM or SOCK_DGRAM. Protocol – protocol to be used, normally IPPROTO_TCP or IPPROTO_UDP.
Relevant Code WSAGetLastError() – returns the error status for the last Windows Sockets operation that failed. Thread specific, like GetLastError(). WSACleanup() – terminates the use of Winsock 2 DLL.
Endianness PCs are little endian machines while TCP/IP protocols use big endian format which is why the address and port numbers require non trivial convertion.
Relevant Code SOCKADDR_IN – A data type containing the IP address of a server and relevant port number : sin_family – Address family, normally AF_INET. sin_addr.s_address – IP address (note the format) sin_port – Port number (note the format) SOCKADDR_IN is used for little endian machines.
Relevant Code connect(SOCKET s, sockaddr *name, int namelen) – binds a socket to an address+port send(SOCKET s, char *buf, int len, int flags) – sends an array of characters through the socket. s – socket buf – the array to be sent len – size of data in the array flags – irrelevant Note : send returns the number of bytes that were actually sent. It might be less than len.
Relevant Code recv(SOCKET s, char *buf, int len, int flags) – reads received data from the socket. s – socket buf – the array to which data will be read len – maximum number of bytes to be read flags – irrelevant Note : recv returns the number of bytes that were actually read. Normally less than len. closesocket(SOCKET s) – closes the socket.
Blocking Functions Send() and Recv() are blocking functions. Very often, it’s necessary to treat incoming and outgoing data independantly and as soon as it’s available. This calls for using threads (or waiting 2 weeks for non blocking implementations).
Important notes It’s necessary to add ws2_32.lib to the list of included library files in the VS6 project. Code files now have to come with a.cpp extension. Need to add #include to the codeץ