Sockets API in Systems Programming: Understanding TCP and UDP Communication, Study notes of Computers and Information technologies

An introduction to the sockets application programmer interface (api) used in systems programming for configuring and using tcp and udp communication protocols. It covers the differences between tcp and udp, the sequence of primitives for both protocols, and the usage of various functions such as socket(), bind(), listen(), connect(), accept(), send(), recv(), sendto(), recvfrom(), setsockopt(), shutdown(), and closesocket().

Typology: Study notes

2010/2011

Uploaded on 09/10/2011

aristocrat
aristocrat 🇬🇧

5

(5)

240 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
11
Systems Programming
Introduction to the
Sockets API
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Sockets API in Systems Programming: Understanding TCP and UDP Communication and more Study notes Computers and Information technologies in PDF only on Docsity!

11

Systems Programming

Introduction to the

Sockets API

Image from http://www.tcpipguide.com

TCP/IP

Protocol Family

Developing Networked Applications – TCP and UDP key facts in brief

  1. TCP is a far more complex protocol than UDP.
    • TCP supports flow control, congestion control, sequence numbers and automatic retransmission if a segment is lost, to ensure reliability.
    • UDP is a minimal protocol, and not reliable.
  2. TCP forms Virtual Connections , which means that before data can be sent a connection must be set up, and after data transmission is complete, the connection must be removed. UDP is Connectionless , it enables immediate sending of data without any additional handshaking.
  3. TCP communication is always one-one. UDP communication can be one-one, or broadcast (one to all).

55 Sockets API - Overview The sockets Application Programmer Interface (API) is an interface that a programmer uses to configure and use the TCP and UDP communication protocols from within an application. The central concept is that ‘sockets’ within each communicating process are connected together. TCP and UDP work in the Transport layer, thus this is a ‘ Virtual ’ socket, i.e. it is a structure in memory that represents the endpoint for communication, it is NOT a physical socket. Network Computer 1 Process 1 Computer 2 Process 2 Process 3 Process 4 Virtual Sockets Communication endpoints for transport-layer process-process communication Physical Sockets (e.g. where you plug an Ethernet cable). Nothing to do with TCP or UDP

77 Sockets API – TCP Primitives sequence

  1. The socket primitive is used to create a socket.
  2. The bind primitive is used to map a process to a port.
  3. The listen, connect and accept primitives are used to set up a connection.
  4. The send primitive is used to send data to another process.
  5. The recv primitive is used to retrieve data from the receive buffer.
  6. The shutdown primitive is used to close the connection.
  7. The closesocket primitive is used to close the socket. A typical exchange could be: Process1 socket bind listen accept send recv Process2 socket connect recv send Process1 send recv shutdown closesocket Process2 recv send shutdown closesocket Time

Sockets API - 1 socket() - create a new socket, identified by an integer number. Used with TCP and UDP. Prototype: SOCKET socket( int AddressFamily , int Type , int Protocol ) Types: SOCK_DGRAM (for UDP), SOCK_STREAM (for TCP) Return parameter SOCKET is derived from an integer type and identifies the socket Example: SOCKET m_ReceiveSOCKET; m_ReceiveSOCKET = socket(AF_INET, SOCK_DGRAM, PF_UNSPEC); if(INVALID_SOCKET == m_ReceiveSOCKET) { MessageBox("Could not create socket","Simple Receive Dialog"); }

Sockets API - 3 listen() is used on the server side, after ‘bind’. This sets the socket into listening-for-connection state. This is only used with TCP sockets. Prototype: int listen( SOCKET s , int backlog ); If no error occurs, listen returns zero. Otherwise, it returns an error code backlog is the maximum length of the queue of pending connections. Example: iResult = listen(m_iSocket, 5 ); if(SOCKET_ERROR == iResult) { MessageBox("Listen failed"); exit(1); }

Sockets API - 4 connect() is used on the client side, to establish a new TCP connection with another process. This is only needed with TCP sockets. Prototype: int connect( SOCKET s , const struct sockaddr* name , int namelen ); If no error occurs, connect returns zero. Otherwise, it returns an error code namelen is the size of the sockaddr structure Example: iError = connect(m_iSocket, (const SOCKADDR FAR*)&m_ConnectSockAddr, sizeof(m_ConnectSockAddr)); if(SOCKET_ERROR == iError) { MessageBox("Connect failed","Client"); }

Sockets API - 6 send() is used to send data, over a TCP connection. Prototype: int send( SOCKET s , const char* buf , int len , int flags ); If no error occurs, send returns the number of bytes sent. Otherwise, it returns an error code. buf is the area of memory containing the message to send len is the size of the message in the buffer flags can be used to specify some control options Example: int iBytesSent; iBytesSent = send(m_ConnectSocket , (char *) &Message, sizeof(Message_PDU), 0); if(SOCKET_ERROR == iBytesSent) { MessageBox("Failed to send","Server"); }

Sockets API - 7 recv() is used to check the local buffer to see if any messages have been received and placed there (used with a TCP connection). If there is a message in the buffer, recv passes it to the application. Prototype: int recv( SOCKET s , char* buf , int len , int flags ); If no error occurs, recv returns the number of bytes received. If the connection has been closed, the return value is zero. Otherwise, it returns an error code. buf is the area of memory that will contain the message len is the size of the buffer (i.e. the maximum amount of data that can be retrieved in one go). flags can be used to specify some control options Example: int iBytesRecd; iBytesRecd = recv(m_iSocket, (char *) &Message, sizeof(Message_PDU), 0); if(SOCKET_ERROR == iBytesRecd) { MessageBox("Receive failed","Client"); } (^) Systems Programming Richard Anthony, Computer Science, The University of Greenwich

Sockets API - 9 recvfrom() is used to check the local buffer to see if any messages have been received and placed there (used with UDP). If there is a message in the buffer, recvfrom passes it to the application. Prototype: int recvfrom( SOCKET s , char* buf , int len , int flags , struct sockaddr* from , int* fromlen ); If no error occurs, recvfrom returns the number of bytes received. If the connection has been closed, the return value is zero. Otherwise, it returns an error code. buf is the area of memory that will contain the message len is buffer size (i.e. max amount of data that can be retrieved in one go) flags can be used to specify some control options from is a sockaddr structure containing the sender’s address (optional) fromlen is the length of the address structure Example: int iBytesRecd = recvfrom(m_ReceiveSOCKET, (char FAR*)m_szRecvBuf, RECEIVE_BUFFER_SIZE, 0, NULL, NULL); if(SOCKET_ERROR == iBytesRecd) { MessageBox(“No message in the buffer","Simple Receive Dialog"); }

Sockets API - 10 setsockopt() is used to set options concerning the way sockets are used. For example to enable UDP to operate in Broadcast mode. Prototype: int setsockopt( SOCKET s , int level , int optname , const char* optval , int optlen ); If no error occurs, setsockopt returns zero. Otherwise, it returns an error code level is the level at which the option applies (usually SOL_SOCKET ) optname is the name of the option to set optval is the value to set the option to optlen is the length of the value data Example: char cOpt[2]; cOpt[0] = 1; // true cOpt[1] = 0; // null terminate the option array int iError = setsockopt(m_SendSOCKET, SOL_SOCKET, SO_BROADCAST, cOpt, sizeof(cOpt)); if(SOCKET_ERROR == iError) { MessageBox("setsockopt() Failed!","Simple Send Dialog"); }

Sockets API - 12 closesocket() close the socket. Used with TCP and UDP. Prototype: int closesocket( SOCKET s ); If no error occurs, closesocket returns zero. Otherwise, it returns an error code. Example: int iError = closesocket(m_ConnectSocket); if(SOCKET_ERROR == iError) { MessageBox(" closesocket() Failed!","Send Dialog"); }