1 / 71

Data Communications and Networking

Data Communications and Networking. Socket Programming Part I: Preliminary Reading: Appendix C - Sockets: A Programmer’s Introduction Data and Computer Communications, 8th edition By William Stallings Reference:

aderes
Download Presentation

Data Communications and Networking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Communications and Networking Socket Programming Part I: Preliminary Reading:Appendix C - Sockets: A Programmer’s Introduction Data and Computer Communications, 8th edition By William Stallings Reference: Internetworking With TCP/IP, Volume III: Client-Server Programming And Applications, Windows Socket Version By Douglas E. Comer and David L. Stevens.

  2. Learning Outcomes • Knowledge • Explain the principles of network programming • Explain the client-server model • Get familiar with WinSock APIs • Skills • Design and develop the client side of client-server network applications using socket programming

  3. Outline • Client Server Model • Concept of Socket • Address Structures • Byte order • WinSock API • Client Software Design • TCP • UDP

  4. Client Server Model • TCP/IP allows two application programs to pass data back and forth • The applications can execute on the same machine or on different machines • How to organize the application programs? • Client-server paradigm is the most popular model • The communication applications are divided into two categories: client and server • Client-server paradigm uses the direction of initiation to categorize whether a program is a client or server.

  5. Client Server Model (Cont.) • An application that initiates the communication is called a client • E.g., Web browser, FTP client, Telnet client, Email client • The client contacts a server, sends a request, and awaits a response • An application that waits for incoming communication requests from clients is called a server • E.g., Web server, FTP server, Telnet server, SMTP server • The server receives a client’s request, performs the necessary computation, and returns the result to the client • Remark: A server is usually designed to provide service to multiple clients • How ???

  6. Client Programs: Web browsers Client Server Model (Cont.) Remark: Because the Web servers and Web browsers are designed based on HTTP, different Web browsers can communicate with all kinds of Web servers.

  7. Time Service: An Example • Time service: based on Time Protocol (RFC868) • http://www.faqs.org/rfcs/rfc868.html • The Time service sends back to the originating source the time in seconds since midnight on January first 1900 • Can use TCP or UDP • Time protocol (when using UDP): • Server: Listen on port 37. • Client: Send an empty datagram to port 37. • Server: Receive the empty datagram. • Server: Send a datagram containing the time as a 32 bit binary number. • Client: Receive the time datagram.

  8. Time Service: Server Program #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <stdarg.h> #include <winsock2.h> #define SA struct sockaddr #define MAXLINE 4096 #define S_PORT 37 #define WINEPOCH 2208988800 int main(int argc, char **argv) { WSADATA wsadata; struct sockaddr_in servaddr, cliaddr; char buff[MAXLINE]; time_t ticks; /* current time */ int n, len; SOCKET s; if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); /* Fill up the servaddr */ memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(S_PORT); s = socket(AF_INET, SOCK_DGRAM, 0); if (s == INVALID_SOCKET) errexit("cannot create socket: error number %d\n", WSAGetLastError()); /* Bind the servaddr to socket s */ if (bind(s, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR) errexit("can't bind to port %d: error number %d\n", S_PORT, WSAGetLastError()); for ( ; ; ) { len = sizeof(SA); if (n = recvfrom(s, buff, sizeof(buff), 0, (SA *)&cliaddr, &len) == SOCKET_ERROR) errexit("recvfrom error: error number %d\n", WSAGetLastError()); time(&ticks);/* returns the number of seconds elapsed since midnight of January 1, 1970 */ ticks = htonl((u_long)(ticks + WINEPOCH)); sendto(s, (char *)&ticks, sizeof(ticks), 0, (SA *)&cliaddr, sizeof(cliaddr)); } /* end of for loop */ }

  9. Time Service: Client Program #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <stdarg.h> #include <winsock2.h> #define SA struct sockaddr #define MAXLINE 4096 #define S_PORT 37 #define WINEPOCH 2208988800 int main(int argc, char **argv) { WSADATA wsadata; SOCKET s; int n, len; time_t now; struct sockaddr_in servaddr; /* Must initialize the socket DLL first */ if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) errexit("WSAStartup failed\n"); if (argc != 2) errexit("usage: daytimeudpcli <IPaddress>"); /* Create a socket, and check the return value */ if ( (s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET ) errexit("socket error: error number %d\n", WSAGetLastError()); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(S_PORT); if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE) errexit("inet_addr error: error number %d\n", WSAGetLastError()); sendto(s, NULL, 0, 0, (SA *)&servaddr, sizeof(servaddr)); len = sizeof(SA); n = recvfrom(s, (char *)&now, sizeof(now), 0, (SA *)&servaddr, &len); if (n == SOCKET_ERROR) errexit("recvfrom failed: error number %d\n", WSAGetLastError()); now = ntohl((u_long)now); now -= WINEPOCH; printf("%s", ctime(&now)); WSACleanup(); return 0; }

  10. How to Write Network Applications? • TCP/IP is implemented inside the OS • OS exports the TCP/IP functionalities through SOCKET APIs • API: Application Program Interface • A set of functions • Programmers develop network applications by using SOCKET APIs • To learn SOCKET programming • Learn some data structures • Learn the socket APIs • Learn multi-threading

  11. Socket Abstraction • “Socket” is an interface between applications and the network services provided by OS • An application sends and receives data through a socket Application SOCKET API TCP/IPv4 TCP/IPv6 UNIX

  12. Socket Abstraction (Cont.) Process B Process A data data data socket socket

  13. Socket Abstraction (Cont.) Web Server Browser B Browser A socket socket socket Browser C

  14. History of Sockets • In early 1980s, the Advanced Research Projects Agency (ARPA) funded a group at UC Berkeley to transport TCP/IP software to the UNIX operating system. • As part of the project, the designers created an interface that applications use for network communication. • The interface used an abstraction known as a socket, and the API became known as socket API. • Many computer vendors adopted the Berkeley UNIX operating system, and the socket interface became very popular. • Subsequently, Microsoft chose the socket interface as the primary network API for its operating systems, called WinSock. • Old version: Windows Sockets 1.1 • Today’s version: Windows Sockets 2 • http://www.sockets.com/winsock2.htm • The important header file: winsock2.h • The socket interface has become a de facto standard throughout the computer industry.

  15. Specifying a Protocol Interface • The designers at Berkeley wanted to accommodate multiple sets of communication protocols. • TCP/IP was not the only choice at that time! • They allowed for multiple families of protocols, with TCP/IP represented as a single family. E.g., • PF_INET or AF_INET (IPv4) • Our focus • PF_INET6 or AF_INET6 (IPv6) • PF_UNIX or AF_UNIX (Unix domain protocols) • PF_IPX or AF_IPX (IPX protocols)

  16. Socket Descriptors • To perform file I/O, we use a file descriptor. • Similarly, to perform network I/O, we use a socket descriptor: • Each active socket is identified by its socket descriptor. • The data type of a socket descriptor is SOCKET. • Hack into the header file winsock2.h: • typedef u_int SOCKET; /* u_int is defined as unsigned int */ • In UNIX systems, socket is just a special file, and socket descriptors are kept in the file descriptor table. • The Windows operating system keeps a separate table of socket descriptors (named socket descriptor table, or SDT) for each process.

  17. How to Create a Socket? • The socket API contains a function socket() that can be called to create a socket. E.g.: The socket is not usable yet. We need to specify more information before using it for data transmission. #include <winsock2.h> … SOCKET s; … s = socket(AF_INET, SOCK_DGRAM, 0) ;

  18. Types of Sockets • Under protocol family AF_INET • Stream socket • Uses TCP for connection-oriented reliable communication • Identified by SOCK_STREAM • s = socket(AF_INET, SOCK_STREAM, 0) ; • Datagram socket • Uses UDP for connectionless communication • Identified by SOCK_DGRAM • s = socket(AF_INET, SOCK_DGRAM, 0) ; • RAW socket • Uses IP directly • Identified by SOCK_RAW • Advanced topic. Not covered by COMP2330.

  19. System Data Structures for Sockets • When an application process calls socket(), the operating system allocates a new data structure to hold the information needed for communication, and fills in a new entry in the process’s socket descriptor table (SDT) with a pointer to the data structure. • A process may use multiple sockets at the same time. The socket descriptor table is used to manage the sockets for this process. • Different processes use different SDTs. • The internal data structure for a socket contains many fields, but the system leaves most of them unfilled. The application must make additional procedure calls to fill in the socket data structure before the socket can be used. • The socket is used for data communication between two processes (which may locate at different machines). So the socket data structure should at least contain the address information, e.g., IP addresses, port numbers, etc.

  20. System Data Structures for Sockets (Cont.) Fig 5.2 from Comer. Conceptual operating system (Windows) data structures after five calls to socket() by a process. The system keeps a separate socket descriptor table for each process; threads in the process share the table.

  21. C Review: Structure • C structures are collections of related variables under one name. struct employee { char firstname[20]; char lastname[20]; int age; float salary; }; typedef struct employee Employee; Employee em; Employee *pEm; /* pointer to structure */ em.salary = 23456; /* dot operator */ pEm = &em; /* assign address of em to pEm */ pEm->salary += 1000; /* struct pointer operator */

  22. memset() and memcpy() memset(): set buffer to a specified character void *memset(void *dest, int c, size_t count); • dest : Pointer to destination. • c : Character to set. • count : Number of characters memcpy(): copy characters between buffers void *memcpy(void *dest, const void *src, size_t count); • dest : New buffer. • src : Buffer to copy from. • count : Number of bytes to copy.

  23. Addressing Issue • How to identify a communication? • Source IP Address, Source Port Number, Destination IP Address, Destination Port Number • TCP or UDP • IPv4 address: 32-bit • Port number: 16-bit • http://www.iana.org/assignments/port-numbers • Better to have a data structure that contains the addressing information • To simplify the socket APIs • Number of function parameters can be decreased

  24. Specifying an Endpoint Address • When a socket is created, it doesn’t contain address information of either local machine or the remote machine. • Before an application uses a socket for sending/receiving data, it must specify one or both of these addresses for the socket. • This can simplify the APIs. • TCP/IP define a communication endpoint to consist of an IP address and a protocol port number. • when you create the socket, you already specified whether this socket is using TCP or UDP. • Several data structures are involved to represent the endpoint address • A general structure: struct sockaddr • A specific structure for IPv4: struct sockaddr_in

  25. Generic Address Structure • The socket system defines a generic endpoint address: • (address family, endpoint address in that family) • The purpose is to provide a common interface for different kinds of protocol families struct sockaddr { u_short sa_family; /* address family */ char sa_data[14]; /* up to 14 bytes of direct address */ }; • Unfortunately, not all address families define endpoints that fit into the sockaddr structure! • To keep program portable and maintainable, TCP/IP code should not use the sockaddr structure in declarations. • Instead, another structure sockaddr_in should be used to represent a socket address in AF_INET family.

  26. TCP/IP Endpoint Address • TCP/IP (IPv4) endpoint address is defined as: (AF_INET, 2-byte port number, 4-byte IP address, 8-byte zero). struct sockaddr_in { short sin_family; /* type of address, always AF_INET */ u_short sin_port; /* protocol port number */ struct in_addr sin_addr; /* IP address */ char sin_zero[8]; /* unused */ }; The IP address is stored in structure sin_addr with type structin_addr: struct in_addr { union { struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b; struct { u_short s_w1,s_w2; } S_un_w; u_long S_addr; } S_un; #define s_addr S_un.S_addr … }; The 32-bit IP address can be explained as 4 unsigned bytes, or 2 unsigned short, or an unsigned long. By using a union, you can manipulate the IP address conveniently.

  27. sockaddr vs. sockaddr_in struct sockaddr_in struct sockaddr 2 bytes 2 bytes sa_family sin_family sin_port 2 bytes 4 bytes sin_addr sa_data 14 bytes sin_zero 8 bytes A pointer to a struct sockaddr_in can be cast to a pointer to a struct sockaddr and vice-versa.

  28. Remark: 2662729985 = 10011110101101100000100100000001 1 182 158 9 An Example • To specify an endpoint address 158.182.9.1:5678 #include <winsock2.h> … struct sockaddr_in addr; … addr.sin_family = AF_INET; addr.sin_port = htons(5678); addr.sin_addr.s_addr = htonl(2662729985); • There are several ways to specify an IP address: • Use a string – Good! • “158.182.9.1” • Use an integer – Bad! • 2662729985 • Use DNS service – Good!

  29. Byte Ordering • Byte Ordering: • Memory is organized in bytes. • E.g, a 16-bit integer takes 2 consecutive bytes; a 32-bit integer takes 4 consecutive bytes. • Different machines use different host bye orderings: • little-endian: least significant byte located at lower memory • E.g., Intel 80x86 • big-endian: least significant byte located at higher memory • E.g., Motorola 68000 • These machines may communicate with one another over the network, and they may have different understandings on the same data. • Not a problem for data type char

  30. Big-Endian Computer Little-Endian Computer Chaos of Byte Order Send out an integer 169283078 Receive an integer 68032266!

  31. Solution: Network Byte Order • Let’s have some regulation! • Network byte order is defined as big-endian byte order • Integers should be sent out in network byte order • The members sin_port and sin_addr in structsockaddr_inshould be in network byte order • sin_port: TCP or UDP port number, put into the TCP/UDP header • sin_addr: IP address, put into the IP header • The member sin_family will not be sent out to the network. So it is not necessary to be in network byte order. • If your application needs to transfer integers between two machines, you should transfer them into network byte order. • You don’t know the type of CPU that executes your program!

  32. Network Byte Order • When sending out an integer • Transfer it into network byte order by: • u_short htons (u_short host_short); • u_long htonl (u_long host_long); • After receiving an integer • Transfer it into (local) host byte order by: • u_short ntohs (u_short network_short); • u_long ntohl (u_long network_long); • Remark: • u_short: unsigned 16-bit integer • u_long: unsigned 32-bit integer h: host n: network s: short l: long h-to-n-s h-to-n-l n-to-h-s n-to-h-l

  33. WinSock API

  34. WinSock API

  35. A TCP Client-Server Example CLIENT SIDE SERVER SIDE WSAStartup() Remark: The server runs forever. It waits for a new connection on the well-known port, accepts the connection, interacts with the client, and then closes the connection. socket() WSAStartup() bind() socket() listen() connect() accept() send() recv() send() recv() closesocket() closesocket() WSACleanup() WSACleanup()

  36. A UDP Client-Server Example UDP Server UDP Client WSAStartup() WSAStartup() socket() socket() bind() data (request) recvfrom() sendto() process request data (reply) recvfrom() sendto() closesocket() closesocket() WSACleanup() WSACleanup()

  37. Comparison Between TCP and UDP • Common function calls • WSAStartup(), WSACleanup() • socket(), closesocket() • bind() • Differences • TCP is connection-oriented, UDP is connectionless • TCP applications use listen(), accept(), connect() to setup TCP connections • Data transfer • TCP applications use send() and recv() • UDP applications use sendto() and recvfrom()

  38. WSAStartup() • Programs using WinSock must call WSAStartup() before using sockets. It is needed because the operating system uses dynamically linked libraries (DLLs). • int WSAStartup ( WORD wVersionRequested, LPWSADATA lpWSAData ); • wVersionRequested: The highest version of Windows Sockets support that the caller can use. The high order byte specifies the minor version (revision) number; the low-order byte specifies the major version number. • lpWSAData: A pointer to the WSADATA data structure that is to receive details of the Windows Sockets implementation. • WSAStartup() returns zero if successful. Example code: WSADATA wsadata; int err; err = WSAStartup(MAKEWORD(2,2), &wsadata); if (err != 0) return;

  39. WSACleanup() • Once an application finishes using and closing sockets, it calls WSACleanup() to deallocate all data structures and socket bindings. • A program usually calls WSACleanup() only when it is completely finished and ready to exit. int WSACleanup(void); The return value is zero if the operation was successful. Otherwise, the value SOCKET_ERROR is returned.

  40. WSAGetLastError() • An application calls the WSAGetLastError function to retrieve the specific error code following an unsuccessful socket function call. • An application should call WSAGetLastError immediately after a socket function returns an error indication. • So that you can know what the problem is. • Windows Sockets Error Codes • http://msdn.microsoft.com/en-us/library/ms740668.aspx int WSAGetLastError(void); The return value indicates the error code for this thread's last Windows Sockets operation that failed.

  41. socket() • The Windows Sockets socket() function creates a socket. • SOCKET socket ( int af, int type, int protocol ); • af: An address family specification. • type: A type specification for the new socket. The following are the only two type specifications supported for Windows Sockets 1.1: SOCK_STREAM and SOCK_DGRAM. In Windows Sockets 2, some new socket types are introduced. • protocol: A particular protocol to be used with the socket that is specific to the indicated address family. Remark: we usually set it as 0. • If no error occurs, socket() returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is returned. Example code: SOCKET s; s = socket(AF_INET, SOCK_STREAM, 0); if (s == INVALID_SOCKET) { printf(“Error code: %d\n”, WSAGetLastError()); return; }

  42. closesocket() • Once a client or server finishes using a socket, it calls closesocket() to deallocate it. • If only one process is using the socket, closesocket() immediately terminates the connection and deallocates the socket. • If several processes share a socket, closesocket() decrements a reference count and deallocates the socket when the reference count reaches zero. int closesocket (SOCKET s); If no error occurs, closesocket() returns zero. Otherwise, a value of SOCKET_ERROR is returned.

  43. Assigning Endpoint Address At the client side: #define S_PORT 13 struct sockaddr_in servaddr; … memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(S_PORT); servaddr.sin_addr.s_addr = inet_addr(argv[1]); Remark: inet_addr() takes an ASCII string that contains a dotted decimal address and returns the equivalent IP address in binary. argv[1] represents the first argument to the command. At the server side: #define S_PORT 13 struct sockaddr_in servaddr; … memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(S_PORT); Remark: INADDR_ANY represents a wildcard address that matches any of the computer’s IP address. In winsock2.h: #define INADDR_ANY (u_long)0x00000000 The client must provide the IP address and port number of the server. The server doesn’t know who will connect to it. It needs to define the local port number only.

  44. How to Get the Server Address? • The client software needs to know the server’s address. • You can: • Include the address into the source code • Not flexible. If the server’s address is changed, you have to recompile your source code. • Require the user to identify the server when invoking the program • the most popular way

  45. inet_addr(): Parsing an Address • The arguments are stored in character strings • E.g., when user input an IP address “128.10.2.3”, your program usually receives just a string. You need to transfer this string into an IP address data structure. unsigned long inet_addr ( const char * cp ); If successful, inet_addr() returns an unsigned long that contains the IPv4 address in binary form using network byte order. Otherwise, inet_addr() returns INADDR_NONE to indicate that the argument does not contain a valid dotted decimal address. Example code: void main (int argc, char * argv[]) { struct sockaddr_in servaddr; … servaddr.sin_addr.s_addr = inet_addr(argv[1]); }

  46. inet_ntoa(): Output an IP Address • char * inet_ntoa(struct in_addr in); • The inet_ntoa() function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in dot notationas in "a.b.c.d''. • Good for output! Example code: char *a; struct sockaddr_in servaddr; … a = inet_ntoa(servaddr.sin_addr); printf(“address is : %s\n”, a);

  47. Looking Up a Domain Name • Internet hosts can be identified by IP address or hostnames. • The Domain Name Service (DNS) provides mapping between hostname and IP address • E.g.: • www.hkbu.edu.hk 158.182.4.1 • www.google.com 66.249.89.104 • How can we use DNS service? • To enjoy DNS services, you must keep the IP address of a default DNS server (or more backups), configured by hand or by DHCP. • Check this out by command “ipconfig /all”. • Every time you need to map a domain name into its corresponding IP address, you call the function gethostbyname(). • It will trigger the OS to contact the DNS server to obtain the IP address.

  48. gethostbyname() • Sometimes one domain name are mapped to a list of IP addresses (e.g., for a cluster server). • Instead of returning a single IP address, it will return a complicated data structure “hostent” which can store a list of IP addresses. • struct hostent { • char * h_name; /* official host name */ • char ** h_aliases; /* other aliases */ • short h_addrtype; /* address type */ • short h_length; /* length of each address in bytes */ • char ** h_addr_list; /* list of addresses */ • #define h_addr h_addr_list[0] • }; • struct hostent * gethostbyname( const char* name); • Example code: • char* server = “www.comp.hkbu.edu.hk”; • struct hostent *h; • … • if ( h = gethostbyname(server) ) • memcpy(&servaddr.sin_addr, h->h_addr, h->h_length); 1. It will return a NULL pointer if error occurs. 2. The returned IP address is in network byte order.

  49. getservbyname() Most client programs must look up the protocol port for the specific service they wish to invoke. To do so, the client invokes library function getservbyname() which takes two parameters: (1) a string that specifies the desired service; (2) a string that specifies the transport protocol being used (i.e., tcp or udp). struct servent { char * s_name; /* official service name */ char ** s_aliases; /* other aliases */ short s_port; /* port for this service */ char * s_proto; /* protocol to use */ }; struct servent getservbyname ( const char * name, const char * proto ); Example code: struct servent *sptr; if ( sptr = getservbyname (“smtp”, “tcp”) ) { /* port number is now in sptr->s_port */ } else { /* error occurred – handle it */ } Another similar library function is getprotobyname(). Check it out by yourself.

  50. bind() • When a socket is first created, it has no associated endpoint addresses. • Function bind() can specify the local endpoint address for a socket. • Usually, a server calls bind() to specify the well-known port at which they will await connections. • A client can skip bind() and let OS to decide. • int bind(SOCKET s, const struct sockaddr * addr, int addrlen); • s: the socket descriptor • addr: a pointer to the address assigned to the socket • addrlen: the size (in bytes) of the real address structure If no error occurs, bind() returns 0. Otherwise, it returns SOCKET_ERROR. • Example code: • SOCKET s; • struct sockaddr_in servaddr; • /* fill in the fields of servaddr */ • … • if ( bind(s, (struct sockaddr*)&servaddr, sizeof(servaddr))== SOCKET_ERROR ) { • /* error handling */ • }

More Related