Download presentation
Presentation is loading. Please wait.
Published byNora Webster Modified over 9 years ago
1
2: Application Layer 1 Socket Programming UNIX Network Programming, http://beej.us/guide/bgnet/ Socket Programming Tutorial:
2
2: Application Layer 2 Socket basics r Socket: a door between application process and end-end-transport protocol (UDP or TCP) r Each host has 65,536 ports r Some ports are reserved, for example: m HTTP: 80 m FTP: 20, 21 m Telnet: 23 r sender explicitly attaches destination IP address and destination port number to each packet r server extracts IP address, port of sender from received packet
3
2: Application Layer 3 High Level View of a Socket: 5-tuple r Type of socket: TCP or UDP r Local Port r Local IP address r Peer’s port (optional for UDP) r Peer’s IP address (optional for UDP)
4
2: Application Layer 4 Struct sockaddr Generic: struct sockaddr { u_short sa_family; /* which address family */ char sa_data[14]; /* the remaining 14 bytes */ }; For the Internet: struct sockaddr_in { short sin_family;/* AF_INET */ u_short sin_port;/* port 0-65535 */ struct in_addr sin_addr;/* IP-address */ char sin_zero[8]; /* unused */ }; struct in_addr { u_long s_addr;/* 32-bit netid/hostid */ };/* network byte ordered */
5
2: Application Layer 5 Byte Ordering: Address and Port r Different Machines use different byte order for storing integers m u_short sin_port is 16 bits m in_addr sin_addr is 32 bits r Big Endian Notation m Most Significant Byte (MSB) to Least Significant Byte (LSB) m The IP address 164.107.112.44 will be stored as r Little Endian Notation m LSB to MSB m The IP address 164.107.112.44 will be stored as r Internet messages must follow Big Endian ordering 164 107 112 44 112 107 164
6
2: Application Layer 6 Byte Ordering Functions for handling byte order differences between Internet and some OSes u_long htonl (u_long hostlong ); u_short htons (u_short hostshort ); u_long ntohl (u_long netlong ); u_short ntohs (u_short netshort ); These functions implicitly assume that short is 16 bits and long is 32 bits If host order is same as network order, the function simply returns the argument network host
7
2: Application Layer 7 Socket System Calls for UDP socket() bind() recvfrom() process data sendto() socket() bind() sendto() recvfrom() blocks until data received from client data (request) data (reply) Client Server Time application viewpoint UDP provides unreliable data delivery service between client and server
8
2: Application Layer 8 socket(): returns socket descriptor for use by later system calls, or -1 on error. r int socket (int family, int type, int protocol); family: set to AF_INET type m SOCK_STREAM : for TCP m SOCK_DGRAM : for UDP m SOCK_RAW : for IP (bypasses transport layer) protocol to "0" to have socket() choose the correct protocol based on the type r Example m sockfd = socket(AF_INET, SOCK_STREAM, 0);
9
2: Application Layer 9 bind(): assigns a port to an unnamed socket r int bind (int sockfd, struct sockaddr *myaddr, int addrlen); int sockfd; struct sockaddr_in my_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(5000); // short, network byte order my_addr.sin_addr.s_addr = inet_addr("10.12.110.57"); memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
10
2: Application Layer 10 sendto(), recvfrom(): send and receive through UDP sockets r int sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen); m Returns number of bytes sent r int recvfrom(int sockfd, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen); m Returns number of bytes received flag is normally set to 0
11
2: Application Layer 11 UDP server #define PORT_NUM 1050 // Port number used void main(void) { unsigned int server_s; // Server socket descriptor struct sockaddr_in server_addr; // Server1 Internet address struct sockaddr_in client_addr; // Client1 Internet address int addr_len; // Internet address length char out_buf[100]; // 100-byte buffer for output data char in_buf[100]; // 100-byte buffer for input data long int i; // Loop counter server_s = socket(AF_INET, SOCK_DGRAM, 0); // Fill-in my socket's address information server_addr.sin_family = AF_INET; // Address family to use server_addr.sin_port = htons(PORT_NUM); // Port number to use server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any IP address bind(server_s, (struct sockaddr *)&server_addr, sizeof(server_addr)); addr_len = sizeof(client_addr); recvfrom(server_s, in_buf, sizeof(in_buf), 0, (struct sockaddr *)&client_addr, &addr_len); printf("Message received is: '%s' \n", in_buf); strcpy(out_buf, "Reply message from server1 to client1"); sendto(server_s, out_buf, (strlen(out_buf) + 1), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); close(server_s); }
12
2: Application Layer 12 UDP client
13
2: Application Layer 13 Socket-programming using TCP TCP service: reliable transfer of bytes from one process to another process TCP with buffers, variables socket controlled by application developer controlled by operating system host or server process TCP with buffers, variables socket controlled by application developer controlled by operating system host or server internet
14
2: Application Layer 14 Socket System Calls for TCP socket() bind() listen() accept() recv() send() socket() connect() send() recv() connection establishment blocks until connection from client data (request) data (reply) Client Server Time
15
2: Application Layer 15 listen(): sets limit on the maximum number of unprocessed incoming requests r int listen (int sockfd, int backlog); r backlog is the number of connections allowed on the incoming queue r typical default is 20
16
2: Application Layer 16 accept(): takes the first queued connection request and creates a new socket call blocks if no pending requests r int accept (int sockfd, void *peer, int *addrlen); r sockfd is the socket descriptor peer will usually be a pointer to a local struct sockaddr_in to find out which host is calling from which port listen(sockfd, 10); sin_size = sizeof(struct sockaddr_in); new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
17
2: Application Layer 17 accept(): for (; ;) { newsockfd = accept (sockfd, …); /* blocks */ if (newsockfd < 0) { fprintf(stderr,“accept error”); exit(0); } if (fork() == 0) { close(sockfd); /* child */ do_something(newsockfd); /*process the request */ exit(0); } close (newsockfd); } for (; ;) { newsockfd = accept (sockfd, …); /* blocks */ if (newsockfd < 0) { fprintf(stderr,“accept error”); exit(0); } do_something(newsockfd); /*process the request */ close (newsockfd); } Iterative Server Concurrent Server
18
2: Application Layer 18 connect(): establishes connection with the server does not return till connection is established or fails to connect r int connect (int sockfd, struct sockaddr *serv_addr, int addrlen); r serv_addr is a struct sockaddr containing the destination port and IP address, r addrlen is set to sizeof(struct sockaddr) r Handshake messages are exchanged between the peers r If called before bind(), OS automatically assigns a port If sockfd is a UDP socket, OS stores peer specific information from serv_addr m Subsequent calls for reading and writing do not require destination address or port number sockfd = socket(AF_INET, SOCK_STREAM, 0); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(DEST_PORT); // short, network byte order dest_addr.sin_addr.s_addr = inet_addr(DEST_IP); memset(&(dest_addr.sin_zero), '\0', 8); // zero the rest of the struct connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr));
19
2: Application Layer 19 send(), recv(): to send and recv data through TCP sockets or connect-ed UDP sockets r int send (int sockfd, const void *msg, int len, int flags); m Returns the number of bytes sent r int recv (int sockfd, void *buf, int len, unsigned int flags); m Returns the number of bytes received flag is normally set to 0
20
2: Application Layer 20 select() to enable a process to wait for events on multiple sockets r int select (int maxfdpl, fd_set *readfds, fd_set *writefds, fd_set *execptfds, struct timeval * timeout); r Returns the number of ready descriptors or, -1 if none maxfdpl : 1+ largest file descriptor to check readfds : List of descriptors for checking if ready to read writefds : List of descriptors for checking if ready to write exceptfds : List of descriptors for checking if any exceptions timeout : timeout value to wait, NULL for infinite timeout struct timeval { long tv_set; /* seconds */ long tv_usec;/* microseconds */ }
21
2: Application Layer 21 select() (contd.) Macros for setting/resetting/checking bits corresponding to sockets r FD_ZERO (int fd, fd_set *fd_set);/* clear all bits in fdset */ r FD_SET (int fd, fd_set *fd_set);/* turn on the bit for fd */ r FD_CLR (int fd, fd_set *fd_set);/* turn off the bit for fd */ r FD_ISSET (int fd, fd_set *fdset); /* test the bit for fd in fdset */
22
2: Application Layer 22 Select example
23
2: Application Layer 23 close() : to close a socket r close (sockfd) m frees socket descriptor m frees the associated port
24
2: Application Layer 24 Address Conversion Routines for conversion between dotted-decimal format and in_addr structure r int inet_aton (const char *cp, struct in_addr *inp) r Dotted decimal string to internet address r char * inet_ntoa (struct in_addr inaddr); r Internet address to string format
25
2: Application Layer 25 Some other useful functions: r Socket Address m getsockname: get IP and port of a socket m getpeername: get IP and port of the other end of the socket r Host Name m Gethostname r Host Information m gethostbyname: get IP address from machine name m gethostbyaddr: get machine name from IP address r Other send recv functions m sendmsg/recvmsg
26
2: Application Layer 26 TCP server
27
2: Application Layer 27 TCP server (contd.)
28
2: Application Layer 28 TCP client
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.