440 likes | 690 Views
Socket Programming in C. Kyounghee Lee leekhe@icu.ac.kr Information and Communications Univ. Outline. TCP/IP introduction TCP/IP overview Transport layer: TCP & UDP Socket fundamentals Socket address and port numbers Network byte ordering & address conversion Socket creation
E N D
Socket Programming in C Kyounghee Lee leekhe@icu.ac.kr Information and Communications Univ
Outline • TCP/IP introduction • TCP/IP overview • Transport layer: TCP & UDP • Socket fundamentals • Socket address and port numbers • Network byte ordering & address conversion • Socket creation • Socket functions • Elementary TCP socket functions • TCP client-server example • Elementary UDP socket functions • UDP client-server example • Programming assignment #01 • Program description • Assignment evaluation
TCP/IP Introduction ICU Information and Communications University
UDP & TCP • UDP • Datagram transmission • Connection less: delivery guarantee (X) • Short-term relationship between client & server • TCP • Connection-oriented: reliability, packet sequence • Flow control & congestion control • Full-duplex • Long-term relationship
TCP Connection Three-way handshake Simultaneous close
UDP Client-Server UDP Server socket() bind() UDP Client recvfrom() socket() blocks until datagram received from a client sendto() data(request) process request recvfrom() sendto() data(reply) close()
Socket Pair • Socket identification • IP address + port number • TCP connection identification • Socket pair • 4-tuple definition • IP address and port number of each endpoint • e.g.) {210.107.128.31.21, 210.107.132.195.1500}
Port numbers • 16-bit integer • Differentiate a socket-related process from another • Ranges • Well-known ports (0 ~1023): assigned by IANA • e.g.) FTP (21), web server (80), … • Registered ports (1024 ~ 49151): recommendation list • e.g.) X Window server (6000 ~ 6003) • Dynamic or private ports (49152 ~ 65535)
Socket Address Structure (1) • Generic IPv4 struct sockaddr { uint8_t sa_len; sa_family_t sa_family; /* address family: AF_XXX value */ char sa_data[14]; /* protocol-specific address */ }; • Posix.1g struct in_addr { in_addr_t s_addr; /* 32 bit IP address */ }; struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */ sa_famility_t sin_family; /* AF_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 */ };
Socket Address Structure (2) • Data types in Posix.1g
Byte Ordering • Big & little-endian byte order • No standard between two types
Network Byte Ordering • Exchanging multi-byte data type • Two end protocol stack must agree on the order type • IP uses big-endian byte ordering • Byte ordering functions
Byte Manipulation Functions • Berkeley-derived functions • ANSI C
Address Conversion Functions • Convert IPv4 address • Between a dotted-decimal string and its 32-bit network byte ordered binary value
Getting an Address of a Socket • Function definition • Retrieves the address binded to a socket with its descriptor
Socket() Function • Definition • Protocol family constants & Socket type • Protocol argument is normally set to 0 except for raw socket
Socket Creation • Example #include <sys/types.h> #include <sys/socket.h> …. int sockfd; …. sockfd = socket(AF_INET, SOCK_DGRAM, 0); ….
Connect() Function • Definition • Generally cast sockaddr_in with (sockaddr *) • Variable ‘errno’ is set to the corresponding error code
Bind() Function • Definition • Specifies a port number and an IP address for a socket • Servers generally bind their well-known port when they start • Clients let the kernel choose an ephemeral port when either connect() or listen() is called
Listen() Function • Definition • Two queues in the kernel for backlog • Incomplete connection queue: SYN_RCVD state • Completed connection queue: ESTABLISHED state
Accept() Function • Definition • Variable cliaddr is set to the corresponding client IP address and port number after a successful return
Close() Function • Definition
Basic TCP Socket I/O • Read() # include <unistd.h> int read(int sockfd, char *ptr, size_t nbytes); Returns: number of bytes read, -1 on error • Write() # include <unistd.h> int write(int sockfd, char *ptr, size_t nbytes); Returns: number of bytes written, -1 on error
Typical I/O Example int readn(int fd, void *vptr, size_t n) { size_t nleft, nread; char *ptr; ptr = vptr; nleft = n; while(nleft > 0) { if((nread = read(fd, ptr, nleft)) < 0) { • if(errno == EINTR) • nread = 0; • else • return –1; } else if (nread == 0) • break; nleft -= nread; ptr += nread; } return n; }
TCP Server Example • Outline for typical concurrent server
TCP Socket Descriptor • Status transition *after return from accept *after socket close() *after fork() returns
Functions for Concurrency • ‘exec’ functions • Difference in 6 functions is • whether the file to execute is specified by a filename or pathname • whether the arguments are passed one by one or array of pointers • whether the environment of the calling process is passed or whether new environment is specified
Simple TCP Server Example (1) • TCP echo server
Simple TCP Server Example (2) • ‘str_echo’ function
Simple TCP Client Example • TCP echo client
Basic UDP Socket I/O (1) • sendto() # include <sys/socket.h> int sendto(int s, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen); Returns: number of bytes sent, -1 on error • recvfrom() # include <sys/socket.h> int recvfrom(int s, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen); Returns: number of bytes received, -1 on error
Basic UDP Socket I/O (2) • “flags” for socket I/O functions • Either 0 or formed by logically OR’ing one or more of the constants shown in the following table • Remark • MSG_DONTROUTE: destination is in the local network • MSG_OOB: message has higher priority than in-band data • MSG_PEEK: let the received data seem to be still available to be read (do not discard from the queue) • MSG_WAITALL:tell to kernel not to return until the request number of bytes have been read
Simple UDP Server Example • #include <sys/socket.h> • #include <sys/types.h> • int main(int argc, char **argv) • { • int sockfd, n, len; • char msg[80]; • struct sockaddr_in servaddr, cliaddr; • sockfd = socket(AF_INET, SOCK_DGRAM, 0); • bzero(&servaddr, sizeof(servaddr)); • servaddr.sin_family = AF_INET; • servaddr.sin_addr.s_addr = htonl(INADDR_ANY); • servaddr.sin_port = htons(1500); • bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); • len = sizeof(cliaddr); • while(1) • { • n = recvfrom(sockfd, msg, 80, 0, (struct sockaddr *)&cliaddr, &len); • sendto(sockfd, msg, n, 0, (struct sockaddr *)&cliaddr, len); • } • }
Simple UDP Client Example (1) • #include <sys/socket.h> • #include <sys/types.h> • #include <string.h> • int main(int argc, char **argv) • { • int sockfd, n; • char sendline[80], recvline[80]; • struct sockaddr_in servaddr; • if(argc != 2) • { • printf(“Usage: uecho <IP address>\n”); • exit(0); • } • sockfd = socket(AF_INET, SOCK_DGRAM, 0); • bzero(&servaddr, sizeof(servaddr)); • servaddr.sin_family = AF_INET; • servaddr.sin_addr.s_addr = inet_addr(argv[1]); • servaddr.sin_port = htons(1500);
Simple UDP Client Example (2) • while(gets(sendline) != NULL) • { • sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *)&servaddr, • sizeof(servaddr); • n = recvfrom(sockfd, recvline, 80, 0, NULL, NULL); • puts(recvline); • } • }
Program Description • Baseball game • User finds three blind numbers (1~9) given by server (e.g. 7 5 9) • User tries 12 times and server replies with X ball Y strike • (e.g. 2 5 7 1 ball & 1 strike) • If a user finds the sequence of 3 numbers before 12 tries, win! • Requirements • Multi-client support (concurrent server) • Both TCP and UDP socket should be used • * UDP: request of game start (designated port, 9000), • reply to the request (user full or accept with port number for connecting) • * TCP: user tries & server replies for game proceeding • Use C or C++ language on UNIX/LINUX systems
Assignment Evaluation (1) • Due date • Mar 21, 11:00 PM • Late submission will be assessed a penalty of 10% for a day • Submission • Implementation report • Full source codes • Send an email to TA (leekhe@icu.ac.kr) • Evaluation factors • Originality (‘S’ or ‘F’) • Operability (40) • Readability (30) • Efficiency (30) • Recommended reference • “UNIX Network Programming”, W. R.Stevens, Prentice Hall
Assignment Evaluation (2) • Implementation Report • Your name and affiliation • Assignment objective • Program functionality • Program design • Implementation environment (platform, OS, programming library, etc.) • Results • How to compile/execute your program • Display the execution results that you have tested • Pros and cons of your implementation • MS Word or PDF file with name of “studentID.doc” or “studentID.pdf” • Source codes • Detailed comments • Including a ‘Makefile’ • All the files should be compressed with a ‘tar’ or ‘zip’ program • The compressed file should be named with “studentID.*”