1 / 59

Sockets

Sockets. Socket API. TCP/IP Model. TCP/IP. TCP/IP does not include an API definition. There are a variety of APIs for use with TCP/IP: Sockets TLI, XTI Winsock MacTCP. Functions needed:. Specify local and remote communication endpoints Initiate a connection

darin
Download Presentation

Sockets

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. Sockets Socket API

  2. TCP/IP Model

  3. TCP/IP TCP/IP does not include an API definition. There are a variety of APIs for use with TCP/IP: Sockets TLI, XTI Winsock MacTCP

  4. 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

  5. Berkeley Sockets Generic: support for multiple protocol families. address representation independence Uses existing I/O programming interface as much as possible. Socket api is similar to file I/O

  6. Socket A socket is an abstract representation of a communication endpoint. Sockets work with Unix I/O services just like files, pipes & FIFOs. Sockets (obviously) have special needs over files: establishing a connection specifying communication endpoint addresses

  7. Unix Descriptor Table

  8. Socket Descriptor Data Structure

  9. Creating a Socket int socket(int family,int type,int proto); family specifies the protocol family (AF_INET for TCP/IP). type specifies the type of service (SOCK_STREAM, SOCK_DGRAM). protocol specifies the specific protocol (usually 0, which means the default).

  10. socket() The socket() system call returns a socket descriptor (small integer) or -1 on error. socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing.

  11. 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.

  12. Necessary Background Information: POSIX data types int8_tsigned 8bit int uint8_tunsigned 8 bit int int16_tsigned 16 bit int uint16_t unsigned 16 bit int int32_tsigned 32 bit int uint32_t unsigned 32 bit int u_char, u_short, u_int, u_long

  13. More POSIX data types sa_family_t address family socklen_tlength of struct in_addr_tIPv4 address in_port_tIP port number

  14. Generic socket addresses struct sockaddr { uint8_t sa_len; sa_family_t sa_family; char sa_data[14]; }; sa_familyspecifies the address type. sa_dataspecifies the address value.

  15. AF_INET For AF_INET we need: 16 bit port number 32 bit IP address

  16. struct sockaddr_in (IPv4) struct sockaddr_in { uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; char sin_zero[8]; }; A special kind of sockaddr structure – used for IPV4 sockets

  17. struct in_addr struct in_addr { in_addr_t s_addr; };

  18. Byte Order

  19. Network Byte Order Network communication uses Bigendian style, also known as Network Byte Order (NBO) All values stored in a sockaddr_inmust be in network byte order. sin_porta TCP/IP port number. sin_addran IP address.

  20. Network Byte Order Functions ‘h’ : host byte order ‘n’ : network byte order ‘s’ : short (16bit) ‘l’ : long (32bit) uint16_t htons(uint16_t); uint16_t ntohs(uint_16_t); uint32_t htonl(uint32_t); uint32_t ntohl(uint32_t);

  21. TCP/IP Addresses We don’t need to deal with sockaddr structures since we will only deal with a real protocol family. We can use sockaddr_instructures. BUT: The C functions that make up the sockets API expect structures of type sockaddr.

  22. Assigning an address to a socket The bind() system call is used to assign an address to an existing socket. int bind( int sockfd, const struct sockaddr *myaddr, int addrlen); bind returns 0 if successful or -1 on error. const!

  23. bind() calling bind()assigns the address specified by the sockaddr structure to the socket descriptor. You can give bind()a sockaddr_instructure: bind( mysock, (struct sockaddr*) &myaddr, sizeof(myaddr) );

  24. bind() Example int mysock,err; struct sockaddr_in myaddr; mysock = socket(PF_INET,SOCK_STREAM,0); myaddr.sin_family = AF_INET; myaddr.sin_port = htons( portnum ); myaddr.sin_addr = htonl( ipaddress); err=bind(mysock, (sockaddr *) &myaddr, sizeof(myaddr));

  25. Uses for bind() There are a number of uses for bind(): Server would like to bind to a well known address (port number). Client can bind to a specific port. Client can ask the O.S. to assign any available port number.

  26. IPv4 Address Conversion int inet_aton( char *, struct in_addr *); Convert ASCII dotted-decimal IP address to network byte order 32 bit value. Returns 1 on success, 0 on failure. char *inet_ntoa(struct in_addr); Convert network byte ordered value to ASCII dotted-decimal (a string).

  27. TCP Client Server socket() “well-known” port bind() listen() Client accept() socket() (Block until connection) “Handshake” connect() Data (request) write() read() Data (reply) write() read() End-of-File close() read() close() Server

  28. TCP Client PF_INETPF_INET6PF_UNIXPF_X25 STREAMDGRAMRAW 0, used by RAW socket sd = socket (family, type, protocol); family port addr three way handshaking ephemeral portip addr (routing) sd = connect (sd, server_addr, addr_len); Server PORT#IP-ADDR write (sd, *buff, mbytes); CONNECT actions 1. socket is valid2. fill remote endpoint addr/port3. choose local endpoint add/port4. initiate 3-way handshaking read (sd, *buff, mbytes); disconnect sequence close (sd);

  29. TCP Server family family port port addr addr sd = socket (family, type, protocol); LISTENSOCKET well-known port #INADDR_ANY bind (sd, *server_addr, len); bind port # 1. Turn sd from active to passive 2. Queue length listen (sd, backlog); three way handshaking CONNECTSOCKET ssd = accept (sd, *cliaddr, *len); read (ssd, *buff, mbytes); write (ssd, *buff, mbytes); disconnect sequence closes socket for R/Wnon-blockingattempts to send unsent datasocket option SO_LINGERblock until data sent close (ssd);

  30. socket() Create a socket familyis one of PF_INET (IPv4), PF_INET6 (IPv6), PF_LOCAL (local Unix), PF_ROUTE (access to routing tables), PF_KEY (encryption) typeis one of SOCK_STREAM (TCP), SOCK_DGRAM (UDP) SOCK_RAW (for special IP packets, PING, etc. Must be root) protocol is 0 (used for some raw socket options) upon success returns socket descriptor Integer, like file descriptor Return -1 if failure int socket(int family, int type, int protocol);

  31. connect()Connect to server sockfd is socket descriptor from socket() servaddr is a pointer to a structure with: port number and IP address must be specified (unlikebind()) addrlen is length of structure client doesn’t need bind() OS will pick ephemeral port returns socket descriptor if ok, -1 on error int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);

  32. bind() Assign a local protocol address (“name”) to a socket sockfd is socket descriptor from socket() myaddr is a pointer to address struct with: port number and IP address if port is 0, then host will pick ephemeral port (very rare for server) How do you know assigned port number? if IP address is wildcard: INADDR_ANY (multiple net cards) host kernel will choose IP address INADDR_ defined in <netinet/in.h> INADDR_ in host byte order => htonl(INADDR_ANY) addrlen is length of structure returns 0 if ok, -1 on error EADDRINUSE (“Address already in use”) int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);

  33. bind() address and port Wildcard specified as INADDR_ANY

  34. listen()Change socket state to TCP server Sockets default to active (for a client) change to passive so OS will accept connection sockfd is socket descriptor from socket() backlog is maximum number of connections that the server should queue for this socket historically 5 rarely above 15 on a even moderate Web server! int listen(int sockfd, int backlog);

  35. listen()

  36. listen() Possibility of SYN flooding attack

  37. accept()Return next completed connection sockfd is socket descriptor from socket() cliaddr and addrlen return protocol address from client returns brand new descriptor, created by OS if used with fork(), can create concurrent server int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);

  38. read() and write() int read (int sockfd, void *buff, size_t mbytes); int write (int sockfd, void *buff, size_t mbytes); Reading and writing packets Both are system calls

  39. close()Close socket for use sockfd is socket descriptor from socket() closes socket for reading/writing returns (doesn’t block) attempts to send any unsent data socket option SO_LINGER block until data sent or discard any remaining data Returns -1 if error int close(int sockfd);

  40. Descriptor Reference Counts For every socket a reference count is maintained, as to how many processes are accessing that socket When close() is called on socket descriptor reference count is decreased by 1 When close() is called on socket descriptor, TCP 4 packet termination sequence will be initiated only if the reference count goes to zero

  41. getsockname() and getpeername() Functions getsockname return the local endpoint address associated with a socket getpeername return the foreign protocol address associated with a socket #include <sys/socket.h> int getsockname(int sockfd, struct sockaddr *localaddr, socklen_t *addrlen); int getpeername(int sockfd, struct sockaddr *peeraddr, socklen_t *addrlen);

  42. getsockname() TCP client that does not call bind, getsockname returns the local IP address and local port number assigned to the connection by the kernel. After calling bind with a port number of 0, getsockname returns the local port number that was assigned. getsockname can be called to obtain the address family of a socket In a TCP server that binds the wildcard IP address, once a connection is established with a client (accept returns successfully), the server can call getsockname to obtain the local IP address assigned to the connection.

  43. getpeername() When a server is execed by the process that calls accept, the only way the server can obtain the identity of the client is to call getpeername inetd server works by execing the respective server’s image

  44. getpeername() : inetd

  45. TCP Echo Client

  46. str_cli function 2 void 3 str_cli(FILE *fp, int sockfd) 4 { 5 char sendline[MAXLINE], recvline[MAXLINE]; 6 while (Fgets(sendline, MAXLINE, fp) != NULL) { 7 Write(sockfd, sendline, strlen (sendline)); 8 if (Read(sockfd, recvline, MAXLINE) == 0) 9 err_quit("str_cli: server terminated prematurely"); 10 Fputs(recvline, stdout); 11 } 12 }

  47. TCP Concurrent Server

  48. TCP Concurrent Server

  49. str_echo function void str_echo(int sockfd) { ssize_t n; char buf[MAXLINE]; again: while ( (n = read(sockfd, buf, MAXLINE)) > 0) Write(sockfd, buf, n); if (n < 0 && errno == EINTR) goto again; else if (n < 0) err_sys("str_echo: read error"); }

More Related