Introduction to Computer Networks Tian Song ( 嵩天 ), Ph.D., Assoc. Prof. songtian@bit.edu.cn
Introduction to Computer Networks Socket and Network Programming Tian Song ( 嵩天 ), Ph.D., Assoc. Prof. songtian@bit.edu.cn
Outline Transport Layer Socket & Network Programming Elements of Transport Protocols 3
Transport Layer Question: Why we need a new layer? Answer: provide reliable connection oriented services provide unreliable connectionless services provide parameters for specifying quality of services 4
Transport Layer Essence: To develop applications, a standard communication interface is required to provide particular services. 5
Transport Layer Features: Logic communication Running in end systems application transport network data link physical network data link physical network data link physical network data link physical network data link physical TCP vs. UDP network data link physical application transport network data link physical 6
Transport Layer Transport Service Primitives : 7
Socket Berkeley Socket: host or server host or server process controlled by app developer process socket socket Process A Process B TCP with buffers, variables Internet TCP with buffers, variables a socket controlled by OS 8
Socket Berkeley Socket: socket API Process A Process B socket API transport layer software transport layer software connection oriented datagram socket 9
Socket Berkeley Socket: 10
Socket Client Server (CS Model) 11
Socket Winsock: Winsock API is supported by a DLL ws2_32.dll / ws2_32.lib / winsock2.h Windows Socket API (WSA) Server Client Mode (CS Mode) Lab2: programming 12
Winsock Server side Procedure WSAStartup(... ); //1. Initialize getaddrinfo (... ); //2. Collect network info socket (... ); //3. Create a socket bind (... ); //4. Bind the socket to IP addr listen (... ); //5. Listen to incoming request accept (... ); //6. If connect request recv, accept send (... ); / recv (... ); //7. Send or receive data : closesocket (... ); //8. Close the socket after using it WSACleanup (... ); //9. Free resource allocated 13
Elements of Transport Protocols Addressing Connection Establishment Connection Release Flow Control and Buffering Multiplexing 14
Addressing Question: How to distinguish different transport services in one end node? Answer: Port ( 端口 ): 0 ~ 65535 source port, destination port 15
Addressing 16
Question: Addressing How do we get to know where the other party is? Well Known Port ( 周知端口 ) 17
Connection Establishment Basic Idea: To establish a connection, you send off a connection request to the other end. The other end then accepts the connection, and returns an acknowledgment. Three way Handshake 18
Transport Layer 19
Connection Establishment Big Problem: What if the unstable network? 20
Connection Establishment Big Problem: What if the unstable network? 21
Connection Release Asymmetric Release one side Symmetric Release two sides 22
Symmetric Connection Release What if the unstable network? 23
Symmetric Connection Release What if the unstable network? 24
Outline Transport Layer Socket & Network Programming Elements of Transport Protocols 25
Attachment Winsock Programming 26
Winsock Initialization To initialize, a nonstandard Winsock specific function WSAStartup() must be the first function to call For example, WORD sockversion; WSADATA wsadata; //Store the socket version //Store socket info sockversion =... ; //Input the version number int iresult = // Return non-zero if error WSAStartup (sockversion, &wsadata); 27
WSAStartup() Parameters sockversion Indicates the highest version of the WinSock DLL you need Returns a non zero value if the DLL cannot support the version you want Can use a macro MAKEWORD to generate the number sockversion = MAKEWORD(2,2); //version 2.2 &wsadata points to a WSADATA structure that returns information on the configuration of the DLL iresult should be equal to zero if successful 28
getaddrinfo() getaddrinfo() provides protocolindependent translation from an ANSI host name to an addr struct addrinfo *result = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; Result kept here hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; iresult = getaddrinfo(null, portno, &hints,&result); if ( iresult!= 0 ) { WSACleanup(); Port number for making the return false; connection, e.g. 8888 } 29Means the School system of Computer will Science be free and Technology, to use any BIT, http://cs.bit.edu.cn/~songtian registered IP addr
addrinfo parameters ai_family = AF_INET denotes the address family. designates the Internet protocol (IP) ai_socktype = SOCK_STREAM specifies connectionoriented (for datagram communications, use SOCK_DGRAM) ai_protocol = IPPROTO_TCP specifies transport layer protocol is TCP ai_flag = AI_PASSIVE indicates the caller intends to use the returned socket address structure in a call to the bind function 30
Create a Socket Call socket() to create (or open) a socket mlistensocket = socket( result->ai_family, result->ai_socktype, result->ai_protocol); if (mlistensocket == INVALID_SOCKET) { freeaddrinfo(result); WSACleanup(); return false; } 31 Assume mlistensocket is a member variable of type SOCKET in your class to store the created socket If create failed, free the memory for result and cleanup everything
Bind to the Socket The bind() function associates a local address with a socket. For example, iresult = bind( mlistensocket, result->ai_addr, (int)result->ai_addrlen); if (iresult == SOCKET_ERROR) { freeaddrinfo(result); closesocket(mlistensocket); result is created in WSACleanup(); getaddrinfo() return false; mlistensocket is } created in socket() freeaddrinfo(result); result is not needed 32 School of Computer Science and Technology, any more, BIT, so http://cs.bit.edu.cn/~songtian free it here
Listen and Accept The listen() function places a socket in a state in which it is listening for an incoming connection Client connection requests will be queued iresult = listen(mlistensocket, SOMAXCONN); if (iresult == SOCKET_ERROR) { closesocket(mlistensocket); WSACleanup(); return false; It is an integer that indicates the } maximum length of the queue of pending connections. If set to SOMAXCONN, the underlying service provider responsible for socket will set the backlog to a 33 School of Computer maximum Science and Technology, reasonable BIT, http://cs.bit.edu.cn/~songtian value.
Listen and Accept (cont) The accept() function permits an incoming connection attempt on a socket SOCKET mclientsocket = accept (mlistensocket, NULL, NULL); //return a new socket with connection It extracts the first connection on the queue of pending connections on the created socket However, if no pending connections are present on the queue, the accept() function can block the caller until a connection is present 34
Send or Receive Data After a connection is established, the server can send or receive data to or from the client Partner stations exchange data using send() and recv() send() and recv() have identical arguments: int send ( int recv ( SOCKET s, SOCKET s, LPSTR lpbuffer, LPSTR lpbuffer, int nbufferlen, int nbufferlen, int nflags); int nflags); 35
send / recv Parameters lpbuffer send: the buffer that keeps the string to be sent recv: the buffer to keep the received string nbufferlen send: the length of the string recv: the size of the buffer used to keep the string nflags Can be used to indicate urgency Can also be used to allow reading the data but not removing it In general, use 0 Return the actual number of bytes transmitted or received. An error is indicated by the value less than or equal to 0 36
send / recv Examples mclientsocket is created by accept() char buffer[default_buflen]; int rval = recv(mclientsocket, buffer, DEFAULT_BUFLEN, 0); //if rval <= 0, error rval = send(mclientsocket, "Hello client, have a nice day!\n", 31, 0); //if rval <= 0, error 37 If no incoming data is available at the socket, the recv call blocks and waits for data to arrive
When Finish When finish transmitting or receiving data, remember to destroy the sockets and release the resource Use closesocket() and WSACleanup() SOCKET mlistensocket, mclientsocket; : //After finish using the socket... closesocket(mlistensocket); closesocket(mclientsocket); WSACleanup(); //Release the resource acquired 38
Example: IP Allocation Given a C class IP: 192.168.1.0/24 1) How many hosts it can support? 2) If we require 4 subnets, how many? 3) How to divide the network into 4? 39
End This page is intended blank. 40