1 / 49

EPL375: Advanced Networks TCP

Overview. Introduction TCP/IP BasicUNIX/C SocketsUDP SocketsTCP SocketsUtility FunctionsOther Socket APISummary. Internet Protocol (IP). Datagram (packet) protocolBest-effort serviceLossReorderingDuplicationDelayHost-to-host delivery (not application-to-application). IP Address. 32-bit

roz
Télécharger la présentation

EPL375: Advanced Networks TCP

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. By: Dr. Vasos Vassiliou Spring 2009 EPL375: Advanced Networks TCP/IP Socket Programming in C

    2. Overview Introduction TCP/IP Basic UNIX/C Sockets UDP Sockets TCP Sockets Utility Functions Other Socket API Summary

    3. Internet Protocol (IP) Datagram (packet) protocol Best-effort service Loss Reordering Duplication Delay Host-to-host delivery (not application-to-application) Host-to-host delivery means that IP takes packets from one host to another host. Datagram service analogy to the post office.Host-to-host delivery means that IP takes packets from one host to another host. Datagram service analogy to the post office.

    4. IP Address 32-bit identifier Identifies a host interface (not a host) We need some way to identify computers on an internetwork The “dotted-quad” representation is just a more readable version of a real 32-bit numberWe need some way to identify computers on an internetwork The “dotted-quad” representation is just a more readable version of a real 32-bit number

    5. Transport Protocols Best-effort is not sufficient !!! Add services on top of IP User Datagram Protocol (UDP) Data checksum Best-effort Transmission Control Protocol (TCP) Data checksum Reliable byte-stream delivery Flow and congestion control

    6. Identifying the ultimate destination IP addresses identify hosts Host has many applications Ports (16-bit identifier) Ports Ports are analogous to phone extensions from main switchboardPorts are analogous to phone extensions from main switchboard

    7. TCP/IP Byte Transport TCP/IP protocols transports bytes Application protocol provides semantics TCP does not examine or modify the bytesTCP does not examine or modify the bytes

    8. Socket How does one speak TCP/IP? Sockets provides interface to TCP/IP Generic interface for many protocols

    10. Socket Identified by protocol and local/remote address/port Applications may refer to many sockets Socket abstraction Berkeley Sockets (traditional) Generic multiple families address representation independence) Uses existing I/O programming interface as much as possible Sockets work with Unix I/O services just like files, pipes Sockets have special needs: establishing a connection specifying communication endpoint addresses

    11. TCP/IP Sockets mySock = socket(family, type, protocol); TCP/IP-specific sockets Socket reference File (socket) descriptor in UNIX Socket handle in WinSock Socket descriptors can be used just like file descriptors in UNIX. In WinSock, Socket handles and file handles are not the same thing.Socket descriptors can be used just like file descriptors in UNIX. In WinSock, Socket handles and file handles are not the same thing.

    12. struct sockaddr { unsigned short sa_family; /* Address family (e.g., AF_INET) */ char sa_data[14]; /* Protocol-specific address information */ }; struct sockaddr_in { unsigned short sin_family; /* Internet protocol (AF_INET) */ unsigned short sin_port; /* Port (16-bits) */ struct in_addr sin_addr; /* Internet address (32-bits) */ char sin_zero[8]; /* Not used */ }; struct in_addr { unsigned long s_addr; /* Internet address (32-bits) */ };

    13. Client: Initiates the connection Server: Passively waits to respond Clients and Servers

    14. Functions needed Specify local and remote communication endpoints Initiate a connection Wait for incoming connection Send and receive data Terminate a connection gracefully Error handling

    15. TCP Client/Server Interaction Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: Accept new connection Communicate Close the connection Students should follow along with source code in the bookStudents should follow along with source code in the book

    16. Creating a Socket int socket(int family, int type, int proto) system call returns a socket descriptor(small integer); -1 on error allocates resources needed for a communication endpoint; does not deal with endpoint addressing family specifies the protocol family AF_INET for TCP/IP type specifies the type of service(communication) SOCK_STREAM, SOCK_DGRAM protocol specifies the specific protocol usually 0 which means the default

    18. Specifying an Endpoint Address Remember that the sockets API is generic There must be a generic way to specify endpoint addresses TCP/IP requires an IP address and a port number for each endpoint address. Other protocol suites(families) may use other schemes. Generic socket addresses(The C function that make up the sockets API expect structures of type sockaddr.) : struct sockaddr { unsigned short sa_family; //specifies the address type char sa_data[14]; //specifies the address value };

    19. Assigning an address to a socket int bind(int socket, (struct sockaddr *) address, int address_length); The bind() system call is used to assign an address to an existing socket. bind returns 0 if successful or -1 on error Example: struct sockaddr_in sin; int s; s = socket(AF_INET, SOCK_DGRAM, 0); sin.sin_family = AF_INET; sin.sin_port = htons(9999); sin.sin_addr.s_addr = INADDR_ANY; bind(s, (struct sockaddr *)&sin, sizeof(sin));

    20. listen() connect() -- TCP Sockets int listen(int socket, int qlength) allows servers to prepare a socket for incoming connections puts the socket in a passive mode ready to accept connections informs the OS that the protocol software should enqueue multiple simultaneous requests that arrive at the socket applies only to sockets that have selected reliable stream delivery service int connect(int, struct sockaddr *dest_addr, int); binds a permanent destination to a socket changes the socket state from unconnected state to connected state The semantics of connect depend on the underlaying protocol TCP connection (AF_INET, reliabe stream delivery service) just store the destination address locally (connectionless)

    21. accept() -- TCP Sockets int accept(int, struct sockaddr * addr, int * addrlen) needs to wait for a connection blocks until a connection request arrives addrlen is a pointer to an integer; when a request arrives , the system fills in argument addr with the address of the client that has placed the request and sets addrlen to the length of the address. system creates a new socket, returns the new socket descriptor

    22. send() and recv() -- TCP Sockets int send(int s, const char *msg, int len, int flags) connected socket argument flags controls the transmission. allows the sender to specify that the message should be sent out-of- band messages correspond to TCP’s urgent data allows the caller to request that the message be sent without using local routine tables (take control of routine) int recv(int s, char *buf, int len, int flags) connected socket argument flags allow the caller to control the reception look ahead by extracting a copy of the next incoming message without removing the message from the socket

    23. close() and shutdown() close(int socket) For UDP sockets, this will release the ownership on the local port that is bound to this socket For TCP, this will initiate a two-way shutdown between both hosts before giving up port ownership. shutdown(int socket, int how) f the how field is 0, this will disallow further reading (recv) from the socket. If the how field is 1, subsequent writes (send) will be disallowed. The socket will still need to be passed to close.

    24. Relationship Between Sockets and File Descriptors Socket handles are integer values. In UNIX, socket handles can be passed to most of the low-level POSIX I/O functions. read(s, buffer, buff_length); //s could be a file descriptor too write(s, buffer, buff_length) ; Calling read on an open socket is equivalent to recv if the socket is UDP, then information about the sender of the datagram will not be returned Similarly the write function call is equivalent to send UDP sockets may call connect to use send and write use the socket library functions instead of the file I/O equivalents.

    26. TCP Client/Server Interaction Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Bind socket to a port Set socket to listen Repeatedly: Accept new connection Communicate Close the connection Students should follow along with source code in the bookStudents should follow along with source code in the book

    27. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    28. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    29. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    30. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    31. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    32. TCP Client/Server Interaction Students should follow along with source code in the book A new socket is created on the server that is connected to the client socketStudents should follow along with source code in the book A new socket is created on the server that is connected to the client socket

    33. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    34. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    35. TCP Client/Server Interaction Students should follow along with source code in the bookStudents should follow along with source code in the book

    36. TCP Client/Server Interaction Students should follow along with source code in the book Note that server closes connection socket, not listening socketStudents should follow along with source code in the book Note that server closes connection socket, not listening socket

    37. TCP Tidbits Client send(“Hello Bob”) recv() -> “Hi Jane” Server recv() -> “Hello ” recv() -> “Bob” send(“Hi ”) send(“Jane”) The client must know the server address and port The server discovers the client’s address and port at connectionThe client must know the server address and port The server discovers the client’s address and port at connection

    38. Closing a Connection Echo Client send(string) while (not received entire string) recv(buffer) print(buffer) close(socket) Echo Server recv(buffer) while(client has not closed connection) send(buffer) recv(buffer) close(client socket) In echo application, how does server know when client is done considering it doesn’t know echo string length? Role of closer can (and is in HTTP) be reversedIn echo application, how does server know when client is done considering it doesn’t know echo string length? Role of closer can (and is in HTTP) be reversed

    39. Byte-order Transformations Byte ordering is a function of machine architecture Intel: little-endian Sparc, PowerPC: big-endian Network order: big-endian The byte order for the TCP/IP protocol suite is big endian.

    43. Network Byte Order Functions Functions: u_long m =ntohl(u_long m) network-to-host byte order, 32 bit— u_long m =htonl(u_long m) host-to-network byte order, 32 bit— ntohs(),htons() short (16 bit) Example: struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(9999); sin.sin_addr.s_addr = inet_addr;

    45. unsigned int inet_addr(char *str) str represents an IP address(dotted-quad notation); inet_addr will return it's equivalent 32-bit value in network byte order. This value can be passed into the sin_addr.s_addr field of a socketaddr_in structure -1 is returned if the string can not be interpreted char *inet_ntoa(struct in_addr ip) Converts the 32-bit value which is assumed to be in network byte order and contained in ip to a string The pointer returned by inet_ntoa contains this string. However, subsequent calls to inet_ntoa will always return the same pointer, so copying the string to another buffer is recommended before calling again. Address transformation

    46. Obtaining Information About Hosts, etc. struct hostent *hptr; /*includes host address in binary*/ hptr=gethostbyname(char *name); Ex.:gethostbyname(“www.csc.ncsu.edu”); Struct hostent *hptr; hptr=gethostbyaddr(char *addr,int addrlen, int addrtype); Ex: gethostbyaddr(&addr, 4, AF_INET);

    47. Obtaining Information About Hosts, etc. int inet_addr(char *dotdecimal); Ex.: sin_addr = inet_addr(“152.14.51.129”); struct servent *sptr; /* includes port and protocol */ sptr=getservbyname(char *name, char *proto); Ex.: getservbyname(“smtp”, “tcp”); struct protoent *pptr; /* includes protocol number */ pptr=getprotobyname(char *name); Ex.: getprotobyname(“tcp”);

    48. Others Include files #include <sys/types.h>; #include <sys/socket.h>; #include <netinet/in.h>; #include <arpa/inet.h>; #include <netdb.h>; #include <unistd.h>; #include <signal.h>; #include <stdio.h>; #include <fcntl.h>; #include <errno.h; #include <sys/time.h>; #include <stdlib.h>; #include <memory.h>; Compiling and Linking Under most versions of UNIX (Linux, BSD, SunOS, IRIX) compiling is done as usual: gcc my_socket_program.c -o my_socket_program Solaris: cc my_socket_program.c -o my_socket_program -lsocket -lnsl Programming tips always check the return value for each function call consult the UNIX on-line manual pages ("man") for a complete description

    49. Summary TCP/IP basic UNIX/C Sockets socket() ; bind() ; connect() ; listen() ; accept() ; sendto() ; recvfrom(); send() ; recv() ; read() ; write(); some utility functions

More Related