Presentation is loading. Please wait.

Presentation is loading. Please wait.

TCP/IP Socket Programming in C

Similar presentations


Presentation on theme: "TCP/IP Socket Programming in C"— Presentation transcript:

1 TCP/IP Socket Programming in C

2 Internet protocol suite
Networking Basics Computers running on the Internet communicate to each other using either TCP (Transmission Control Protocol) or UDP (User Datagram Protocol) When you write C programs that communicate over the network, you are programming at the application layer Typically, you don’t need to concern yourself with TCP and UDP layers application presentation session transport network data link physical application TCP, UDP, … IPv4, IPv6 device driver & hardware sockets API Internet protocol suite OSI model

3 TCP Definition TCP guarantees that e.g.
A connection-based protocol that provides a reliable flow of data between two computers e.g. if you want to speak to your aunt, a connection is established when dial her number and she answers TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent (otherwise, and error is reported) e.g. HTTP, FTP, Telnet, etc.

4 UDP Definition UDP is not connection-based like TCP Why we use UDP?
A protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival e.g. sending a letter through the postal service UDP is not connection-based like TCP the order of delivery is not important and is not guaranteed each message is independent of any other Why we use UDP? Some forms of communication don’t require such strict reliability Reliable connection may require extra overhead e.g. Clock server and its clients, Ping,

5 0~1024: reserved for well-known services
Port Definition The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer cf. IP address used for delivering data to the right computer on the network How does the computer know to which application to forward the received data? 0~1024: reserved for well-known services TCP or UDP port app port # data packet 0~65,535

6 Socket Definition One end-point of a two-way communication link between two programs running on a network A socket is bound to a specific port number so that the TCP layer can identify the application that data is destined to be sent The client and server can communicate by writing to or reading from their sockets similar to file descriptor connection request Server Server port port Client Client Port port connection

7 Socket Address Structure
Generic socket address structure IPv4 socket address structure struct sockaddr { uint8_t sa_len; // length of structure unsigned short sa_family; // address family // PF_INET, PF_INET6, PF_UNIX,… char sa_data[14]; // family-specific address info. } struct sockaddr_in { uint8_t sa_len; unsigned short sa_family; // PF_INET in_port_t sin_port; // 16-bit TCP or UDP port number struct in_addr sin_addr; // 32-bit IPv4 address char sin_zero[8]; // unused }

8 TCP Sockets bind() socket() listen() TCP Client TCP Server accept()
blocks until connection from client connection established (TCP three-way handshake) connect() write() data (request) read() process request data (reply) write() read() close() end-of-file notification read() close()

9 socket() and close() e.g. socket() e.g. close()
#include <sys/socket.h> int socket( int family, int type, int protocol ); Returns: non-negative descriptor if OK, -1 on error #include <unistd.h> int close( int sockfd ); Returns: 0 if OK, -1 on error type family AF_INET SOCK_STREAM TCP or SCTP SOCK_DGRAM UDP SOCK_SEQPACKET SCTP SOCK_RAW IPv4 Protocol IPPROTO_TCP IPPROTO_UDP IPPROTO_SCTP e.g. socket() tcp_sockfd = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ); udp_sockfd = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ); e.g. close() close( tcp_sockfd );

10 connect() e.g. connect() #include <sys/socket.h>
int connect( int sockfd, const struct sockaddr * servaddr, socklen_t addrlen ); Returns: 0 if OK, -1 on error e.g. connect() struct sockaddr_in servaddr; ... servaddr.sin_family = PF_INET; servaddr.sin_addr.s_addr = htonl( “ ” ); servaddr.sin_port = htons( 7 ); // 7 for echo service if( connect( sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr) ) < 0 ) { ... }

11 bind() e.g. bind() Process specifies Result
#include <sys/socket.h> int bind( int sockfd, const struct sockaddr * myaddr, socklen_t addrlen ); Returns: 0 if OK, -1 on error Process specifies Result IP address Port Wildcard Kernel chooses IP address and port Non-zero Kernel chooses IP address, process specifies port Local IP address Process specifies IP address and kernel chooses port Process specifies IP address and port e.g. bind() myaddr.sin_family = PF_INET; myaddr.sin_addr.s_addr = htonl( INADDR_ANY ); myaddr.sin_port = htons( 7 ); // 7 for echo service if( bind( sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr) ) < 0 ) { ... }

12 listen() and accept() e.g. listen() #include <sys/socket.h>
int listen( int sockfd, int backlog ); Returns: 0 if OK, -1 on error int accept( int sockfd, struct sockaddr * cliaddr, socklen_t * addrlen ) Returns: non-negative descriptor if OK, -1 on error e.g. listen() #define LISTENQ 5 ... if( listen( mysock, LISTENQ ) < 0 ) { ... } while( 1 ){ clilen = sizeof( cliaddr ); if( ( clisockfd = accept( mysock, (struct sockaddr *)&cliaddr, &clilen ) ) < 0 ) { ... } }

13 recv() and send() e.g. send() and recv() #include <sys/types.h>
#include <sys/socket.h> int recv( int sockfd, void * buff, size_t len, int flags ); int send( int sockfd, const void * buff, size_t len, int flags ); Both return: number of bytes read or written if OK, -1 on error e.g. send() and recv() if( ( n = send( sockfd, buff, len, 0 ) ) != len ){ ... } ... if( ( n = recv( sockfd, buff, BUFMAX, 0 ) ) < 0 ) { ... }

14 UDP Sockets socket() bind() UDP Server UDP Client recvfrom() socket()
blocks until datagram received from client sendto() data (request) process request data (reply) sendto() recvfrom() close()

15 recvfrom() and sendto()
#include <sys/socket.h> ssize_t recvfrom( int sockfd, void * buff, size_t nbytes, int flags, struct sockaddr * from, socklen_t * addrlen ); ssize_t sendto( int sockfd, const void * buff, size_t nbytes, int flags, const struct sockaddr * to, socklen_t addrlen ) Both return: number of bytes read or written if OK, -1 on error e.g. recvfrom() and sendto() #define MAXLINE 255 char mesg[ MAXLINE ]; ... while( 1 ) { if( ( n = recvfrom( sockfd, mesg, MAXLINE, 0, cliaddr, &len ) ) < 0 ) { ... } sendto( sockfd, mesg, n, 0, cliaddr, len ); }

16 Multitasking Two methods Per-client process Per-client thread
use fork() system call Per-client thread use POSIX thread (pthread) Server Client 1 Child 1 Child 3 Child 2 Client 2 Client 3 wait for a new request

17 Per-Client Process e.g. fork() ... while( 1 ) {
clilen = sizeof( cliaddr ); if( ( clisockfd = accept( mysock, (struct sockaddr *)&cliaddr, &clilen ) ) < 0 ) { ... } // fork child process if( ( pid = fork() ) < 0 ) { ... } else if( pid == 0 ) // child process close( mysock ); HANDLE_REQUEST( clisockfd ); exit( 0 ); } // parent process

18 Per-Client Thread e.g. POSIX thread #include <pthread.h>
int pthread_create( pthread_t * tid, const pthread_attr_t * attr, void * (*func)(void *), void * arg ); Returns:0 if OK, positive Exxx value on error e.g. POSIX thread void * HANDLE_REQUEST( void * arg ); ... pthread_t tid; while( 1 ) { addr_len = sizeof( cliaddr ); if( ( clisockfd = accept( mysock, (struct sockaddr *)&cliaddr, &clilen ) ) < 0 ) { ... } if( pthread_create( &tid, NULL, HANDLE_REQUEST,(void *) &clisockfd ) != 0 ) { ... } }

19 Per-Client Thread (cont’d)
void * HANDLE_REQUEST( void * arg ) { int clisockfd; clisockfd = *( (int *)arg ) // guarantees that thread resources are de-allocated upon return pthread_detach( pthread_self() ); // process request ... close( clisockfd ); return( NULL ); }

20 Multiplexing stdin(=0) Client sockfd (=3) sockfd (=4) readset
#include <sys/select.h> #include <sys/time.h> int select( int maxfdp1, fd_set * readset, fd_set * writeset, fd_set * exceptset, const struct timeval * timeout ); Returns: positive count of ready descriptors, 0 on timeout, -1 on error stdin(=0) Client sockfd (=3) sockfd (=4) readset 1 2 3 4 5 6 data

21 Multiplexing (cont’d)
e.g. select() int num_ready; fd_set cur_set, net_set; ... FD_ZERO( &new_set ); FD_SET( 0, &new_set ); FD_SET( sockfd, &new_set ); while( 1 ) { cur_set = new_set; num_ready = select( sockfd+1, &cur_set, NULL, NULL, NULL ); // case 1: request from socket if( FD_ISSET( sockfd, &cur_set ) ) { /* handle request */ } // case 2: user command if( FD_ISSET( 0, &cur_set ) ) { /* handle user command */ } }

22 References Sun Microsystems, “Custom Networking”,
W. Richard Stevens, Bill Fenner, Andrew M. Rudoff, 2004, “UNIX Network Programming 3rd ed. vol. 1”, Pearson Education, Inc. Michael J. Donahoo, Kenneth L. Calvert, 박준철 역, 2001, “TCP/IP 소켓프로그래밍 (C Version)”, 사이텍미디어


Download ppt "TCP/IP Socket Programming in C"

Similar presentations


Ads by Google