TCP/IP Sockets in C: Practical Guide for Programmers. Computer Chat. Internet Protocol (IP) IP Address. Transport Protocols. Ports

Similar documents
TCP/IP Sockets in C: Practical Guide for Programmers. Computer Chat. Internet Protocol (IP) IP Address. Transport Protocols

TCP Network Programming in C

TCP Echo Application: Client & Server. TA: Awad A Younis Class: CS457 Fall 2014

Writing Network Applications using the TCP/IP Protocol Stack: Socket Programming

CS 3516: Computer Networks

Network Programming Week #1. K.C. Kim

Network Socket Programming - 3 BUPT/QMUL

COE 4DN Advanced Internet Communications. Basic Sockets in C (with some Java and Python) version 1, 2015

Network Socket Programming - 3 BUPT/QMUL

CS 640: Computer Networking

1.2 The first Internet (i.e., one of the first packet switched networks) was referred to as the ARPANET.

Sockets. TCP/IP Sockets in C: Practical Guide for Programmers (we are covering all chapters of Part 1; Part 2 is a good sockets API reference)

Lab 0. Yvan Petillot. Networks - Lab 0 1

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Christian Tschudin (basierend auf einem Foliensatz von C. Jelger und T. Meyer) Departement Mathematik und Informatik, Universität Basel

CS321: Computer Networks Introduction to Application Layer

CS321: Computer Networks Socket Programming

Context. Distributed Systems: Sockets Programming. Alberto Bosio, Associate Professor UM Microelectronic Departement

Socket Programming TCP UDP

Tutorial on Socket Programming

Socket Programming. Dr. -Ing. Abdalkarim Awad. Informatik 7 Rechnernetze und Kommunikationssysteme

CLIENT-SIDE PROGRAMMING

CS 43: Computer Networks. 05: Socket Programming September 12-14, 2018

Types (Protocols) Associated functions Styles We will look at using sockets in C Java sockets are conceptually quite similar

Socket Programming. CSIS0234A Computer and Communication Networks. Socket Programming in C

Sockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

ECE 435 Network Engineering Lecture 2

Sockets. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

ECE 435 Network Engineering Lecture 2

A Client-Server Exchange

Oral. Total. Dated Sign (2) (5) (3) (2)

Network Programming Worksheet 2. Simple TCP Clients and Servers on *nix with C.

PA #2 Reviews. set_name, get_name, del_name. Questions? Will be modified after PA #4 ~

SOCKET PROGRAMMING. What is a socket? Using sockets Types (Protocols) Associated functions Styles

The Berkeley Sockets API. Networked Systems Architecture 3 Lecture 4

CSE 333 Lecture 16 - network programming intro

Lecture 24. Thursday, November 19 CS 375 UNIX System Programming - Lecture 24 1

Hybrid of client-server and P2P. Pure P2P Architecture. App-layer Protocols. Communicating Processes. Transport Service Requirements

Socket Programming. Sungkyunkwan University. Hyunseung Choo Copyright Networking Laboratory

Lecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005

Modern System Calls(IPv4/IPv6)

Network Programming in C: The Berkeley Sockets API. Networked Systems 3 Laboratory Sessions

Unix Network Programming

Sockets 15H2. Inshik Song

UNIX Network Programming. Overview of Socket API Network Programming Basics

CSC209H Lecture 9. Dan Zingaro. March 11, 2015

CSE 333 SECTION 6. Networking and sockets

NETWORK AND SYSTEM PROGRAMMING

Network Programming in C. Networked Systems 3 Laboratory Sessions and Problem Sets

CS118 Discussion 1B, Week 1. Taqi Raza BUNCHE 1209B, Fridays 12:00pm to 1:50pm

CSE 333 Lecture network programming intro

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

Piotr Mielecki Ph. D.

Department of Computer Science

Introduction to Socket Programming

Interprocess Communication Mechanisms

Socket Programming for TCP and UDP

Socket Programming 2007/03/28

ICT 6544 Distributed Systems Lecture 5

Simple network applications using sockets (BSD and WinSock) Revision 1 Copyright Clifford Slocombe

CSE 333 Section 3. Thursday 12 April Thursday, April 12, 12

Interprocess Communication Mechanisms

CSE 333 SECTION 8. Sockets, Network Programming

Linux Network Programming, Part 1

CSE 333 SECTION 7. Client-Side Network Programming

Application Programming Interfaces

CSE 333 SECTION 7. Client-Side Network Programming

CSE 333 SECTION 7. C++ Virtual Functions and Client-Side Network Programming

Client-server model The course that gives CMU its Zip! Network programming Nov 27, Using ports to identify services.

1 /* client.c - adapted from code for example client program that uses TCP */ 2 /*Modified by Vincent Chu, Winter

UNIX Sockets. Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E.

목포해양대해양컴퓨터공학과. IPv6 적용

WinSock. What Is Sockets What Is Windows Sockets What Are Its Benefits Architecture of Windows Sockets Network Application Mechanics

CSE 333 Lecture 8 - file and network I/O

Network Programming November 3, 2008

Programming with TCP/IP. Ram Dantu

Socket Programming. What is a socket? Using sockets. Types (Protocols) Associated functions Styles

How do we Communicate? Introduction to Unix Network Programming. What does Alice do? What does Bob do? Two simplest networking programs

Ports under 1024 are often considered special, and usually require special OS privileges to use.

EECS122 Communications Networks Socket Programming. Jörn Altmann

Introduction to Socket Programming

How to write a Measurement Telnet Server

IP Addresses, DNS. CSE 333 Spring Instructor: Justin Hsia

UNIX Sockets. COS 461 Precept 1

Computer Network Lab, SS Fachgebiet Technische Informatik, Joachim Zumbrägel. Overview. Sockets. Sockets in C.

Introduction to Client-Server Model

Chapter 2 Applications and

CompSci 356: Computer Network Architectures Lecture 3: Hardware and physical links References: Chap 1.4, 1.5 of [PD] Xiaowei Yang

CS307 Operating Systems Processes

Processes. Process Concept. The Process. The Process (Cont.) Process Control Block (PCB) Process State

Network programming(i) Lenuta Alboaie

UNIT 1 TCP/IP PROGRAMMING CONCEPTS

CSE 124 Discussion Section Sockets Programming 10/10/17

Network Software Implementations

Unix Network Programming Chapter 4. Elementary TCP Sockets 광운대학교컴퓨터과학과 정보통신연구실 석사과정안중현

ECE322 Systems Programming Project 2: Networking with Matrix Multiplication in C Grant Kimes 12/16/15

Sockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

IP Addresses, DNS. CSE 333 Summer Teaching Assistants: Renshu Gu William Kim Soumya Vasisht

Sockets. 1 Introduction. (Reference:, Gray Chapter 10) Network Programming Lecture Notes by. Turhan TUNALI

Transcription:

TCP/IP Sockets in C: Practical Guide for Programmers Computer Chat! How do we make computers talk? Michael J. Donahoo Kenneth L. Calvert Morgan Kaufmann Publisher $14.95 Paperback! How are they interconnected? Internet Protocol (IP) Internet Protocol (IP)! Datagram (packet) protocol! Best-effort service! Loss! Reordering! Duplication! Delay! Host-to-host delivery IP Address! 32-bit identifier (IPv4, IPv6=128 bits)! Dotted-quad: 192.118.56.25! www.mkp.com -> 167.208.101.28! Identifies a host interface (not a host) 192.18.22.13 209.134.16.123 Transport Protocols Best-effort 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 Ports Identifying the ultimate destination! IP addresses identify hosts! Host has many applications! Ports (16-bit identifier) 1-65,535 Application WWW E-mail Telnet Port 80 25 23 192.18.22.13

Socket Sockets How does one speak TCP/IP?! Sockets provides interface to TCP/IP! Identified by protocol and local/remote address/port! Applications may refer to many sockets! Sockets accessed by many applications! Generic interface for many protocols TCP/IP Sockets Specifying Addresses TCP UDP! mysock = socket(family, type, protocol);! TCP/IP-specific sockets Family Type Protocol SOCK_STREAM IPPROTO_TCP PF_INET SOCK_DGRAM IPPROTO_UDP! Socket reference! File (socket) descriptor in UNIX Generic IP Specific! 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) */ ; s and s TCP / Interaction! : Initiates the connection : Bob : Jane starts by getting ready to receive client connections Hi. I m Bob. Hi, Bob. I m Jane Nice to meet you, Jane.! : Passively waits to respond 2. Assign a port to socket

TCP / Interaction TCP / Interaction /* Create socket for incoming connections */ if ((servsock = socket(pf_inet, SOCK_STREAM, IPPROTO_TCP)) < 0) echoservaddr.sin_addr.s_addr = htonl(inaddr_any);/* Any incoming interface */ echoservaddr.sin_port = htons(echoservport); /* Local port */ if (bind(servsock, (struct sockaddr *) &echoservaddr, sizeof(echoservaddr)) < 0) DieWithError("bind() failed"); TCP / Interaction /* Mark the socket so it will listen for incoming connections */ if (listen(servsock, MAXPENDING) < 0) DieWithError("listen() failed"); TCP / Interaction for (;;) /* Run forever */ clntlen = sizeof(echoclntaddr); if ((clntsock=accept(servsock,(struct sockaddr *)&echoclntaddr,&clntlen)) < 0) DieWithError("accept() failed"); TCP / Interaction TCP / Interaction is now blocked waiting for connection from a client Later, a client decides to talk to the server

TCP / Interaction TCP / Interaction /* Create a reliable, stream socket using TCP */ if ((sock = socket(pf_inet, SOCK_STREAM, IPPROTO_TCP)) < 0) echoservaddr.sin_addr.s_addr = inet_addr(servip); /* IP address */ echoservaddr.sin_port = htons(echoservport); /* port */ if (connect(sock, (struct sockaddr *) &echoservaddr, sizeof(echoservaddr)) < 0) DieWithError("connect() failed"); TCP / Interaction TCP / Interaction echostringlen = strlen(echostring); /* Determine input length */ /* Send the string to the server */ if (send(sock, echostring, echostringlen, 0)!= echostringlen) DieWithError("send() sent a different number of bytes than expected"); if ((clntsock=accept(servsock,(struct sockaddr *)&echoclntaddr,&clntlen)) < 0) DieWithError("accept() failed"); TCP / Interaction TCP / Interaction /* Receive message from client */ if ((recvmsgsize = recv(clntsocket, echobuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); close(sock); close(clntsocket)

TCP Tidbits! knows server address and port! No correlation between send() and recv() send( Hello Bob ) recv() -> Hi Jane recv() -> Hello recv() -> Bob send( Hi ) send( Jane ) Closing a Connection! close() used to delimit communication! Analogous to EOF send(string) while (not received entire string) recv(buffer) send(buffer) close(socket) recv(buffer) while(client has not closed connection) send(buffer) recv(buffer) close(client socket) TCP/IP Byte Transport Constructing Messages beyond simple strings! TCP/IP protocols transports bytes Application byte stream TCP/IP Here are some bytes. I don t know what they mean. Application byte stream TCP/IP I ll pass these to the app. It knows what to do.! Application protocol provides semantics Application Protocol! Encode information in bytes! Sender and receiver must agree on semantics! Data encoding! Primitive types: strings, integers, and etc.! Composed types: message with fields Primitive Types! String! Character encoding: ASCII, Unicode, UTF! Delimit: length vs. termination character 0 77 0 111 0 109 0 10 M o m \n 3 77 111 109

Primitive Types! Integer! Strings of character encoded decimal digits 49 55 57 57 56 55 48 10 1 7 9 9 8 7 0 \n! Advantage: 1. Human readable 2. Arbitrary size! Disadvantage: 1. Inefficient 2. Arithmetic manipulation Primitive Types! Integer Little-Endian Big-Endian! Native representation 0 0 92 246 23,798 246 92 0 0! Network byte order (Big-Endian)! Use for multi-byte, binary data exchange! htonl(), htons(), ntohl(), ntohs() 4-byte two s-complement integer Message Composition! Message composed of fields! Fixed-length fields integer short short! Variable-length fields M i k e 1 2 \n struct tst short x; int y; short z; ; Beware the bytes of padding -- Julius Caesar, Shakespeare! Architecture alignment restrictions! Compiler pads structs to accommodate x [pad] y z [pad]! Problem: Alignment restrictions vary! Solution: 1) Rearrange struct members 2) Serialize struct by-member TCPEcho.c #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */ #include <arpa/inet.h> /* for sockaddr_in and inet_addr() */ #include <stdlib.h> /* for atoi() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #define RCVBUFSIZE 32 /* Size of receive buffer */ void DieWithError(char *errormessage); /* Error handling function */ int main(int argc, char *argv[]) int sock; /* Socket descriptor */ struct sockaddr_in echoservaddr; /* Echo server address */ unsigned short echoservport; /* Echo server port */ char *servip; /* IP address (dotted quad) */ char *echostring; /* String to send to echo server */ char echobuffer[rcvbufsize]; /* Buffer for echo string */ unsigned int echostringlen; /* Length of string to echo */ int bytesrcvd, totalbytesrcvd; /* Bytes read in single recv() and total bytes read */ if ((argc < 3) (argc > 4)) /* Test for correct number of arguments */ fprintf(stderr, "Usage: %s < IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); servip = argv[1]; /* First arg: server IP address (dotted quad) */ echostring = argv[2]; /* Second arg: string to echo */ if (argc == 4) echoservport = atoi(argv[3]); /* Use given port, if any */ else echoservport = 7; /* 7 is the well-known port for the echo service */ /* Create a reliable, stream socket using TCP */ if ((sock = socket(pf_inet, SOCK_STREAM, IPPROTO_TCP)) < 0) /* Construct the server address structure */ memset(&echoservaddr, 0, sizeof(echoservaddr)); /* Zero out structure */ echoservaddr.sin_addr.s_addr = inet_addr(servip); /* IP address */ echoservaddr.sin_port = htons(echoservport); /* port */ /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoservaddr, sizeof(echoservaddr)) < 0) DieWithError("connect() failed"); echostringlen = strlen(echostring); /* Determine input length */ /* Send the string to the server */ if (send(sock, echostring, echostringlen, 0)!= echostringlen) DieWithError("send() sent a different number of bytes than expected");

TCPEcho.c /* receive the same string back from the server */ totalbytesrcvd = 0; printf("received: "); /* Setup to print the echoed string */ while (totalbytesrcvd < echostringlen) /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesrcvd = recv(sock, echobuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalbytesrcvd += bytesrcvd; /* Keep tally of total bytes */ echobuffer[bytesrcvd] = '\0'; /* Terminate the string! */ printf(echobuffer); /* Print the echo buffer */ printf("\n"); /* Print a final linefeed */ close(sock); exit(0); void DieWithError(char *errormessage) perror(errormessage); exit(1); #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), bind(), and connect() */ #include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */ #include <stdlib.h> /* for atoi() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #define MAXPENDING 5 /* Maximum outstanding connection requests */ void DieWithError(char *errormessage); /* Error handling function */ void HandleTCP(int clntsocket); /* TCP client handling function */ int main(int argc, char *argv[]) int servsock; /* Socket descriptor for server */ int clntsock; /* Socket descriptor for client */ struct sockaddr_in echoservaddr; /* Local address */ struct sockaddr_in echoclntaddr; /* address */ unsigned short echoservport; /* port */ unsigned int clntlen; /* Length of client address data structure */ if (argc!= 2) /* Test for correct number of arguments */ fprintf(stderr, "Usage: %s < Port>\n", argv[0]); exit(1); echoservport = atoi(argv[1]); /* First arg: local port */ /* Create socket for incoming connections */ if ((servsock = socket(pf_inet, SOCK_STREAM, IPPROTO_TCP)) < 0) /* Construct local address structure */ memset(&echoservaddr, 0, sizeof(echoservaddr)); /* Zero out structure */ echoservaddr.sin_addr.s_addr = htonl(inaddr_any); /* Any incoming interface */ echoservaddr.sin_port = htons(echoservport); /* Local port */ /* Bind to the local address */ if (bind(servsock, (struct sockaddr *) &echoservaddr, sizeof(echoservaddr)) < 0) DieWithError("bind() failed"); /* Mark the socket so it will listen for incoming connections */ if (listen(servsock, MAXPENDING) < 0) DieWithError("listen() failed"); for (;;) /* Run forever */ /* Set the size of the in-out parameter */ clntlen = sizeof(echoclntaddr); /* Wait for a client to connect */ if ((clntsock = accept(servsock, (struct sockaddr *) &echoclntaddr, &clntlen)) < 0) DieWithError("accept() failed"); /* clntsock is connected to a client! */ printf("handling client %s\n", inet_ntoa(echoclntaddr.sin_addr)); HandleTCP(clntSock); /* NOT REACHED */ Transport Protocols! Best-effort, host-to-host insufficient! Transport protocols add services to IP! Ports make end-to-end protocols Application WWW E-mail Telnet Port 80 25 23 192.18.22.13 Transport Protocols! User Datagram Protocol (UDP)! Adds ports and data checksum to IP! Best-effort! Transmission Control Protocol (TCP)! Adds ports and data checksum to IP! Reliable byte-stream delivery! Flow and congestion control! Etc.

Socket Protocols! Protocol Family! PF_INET Internet Protocol Family! Protocol Type! SOCK_STREAM Reliable byte-stream! SOCK_DGRAM Best-effort datagram! Protocol! IPPROTO_TCP! IPPROTO_UDP TCP using socket() 2. Establish a connection to the server using connect() using send() and recv() with close() TCP using socket() 2. Assign a port number to the socket with bind() 3. Tell the system to allow connections to be made to that port, using listen() 4. Repeatedly do the following: a. Call accept() to get a new socket for each client connection. with the client via that new socket, using send() and recv() c. Close the client connection using close() Protocols! We want to make computers talk! Protocol: Agreement on exchange Bob Jane Hi. I m Bob. Hi, Bob. I m Jane Nice to meet you, Jane. TCPEcho-Fork.c #include "TCPEcho.h" /* TCP echo server includes */ #include <sys/wait.h> /* for waitpid() */ int main(int argc, char *argv[]) int servsock; /* Socket descriptor for server */ int clntsock; /* Socket descriptor for client */ unsigned short echoservport; /* port */ pid_t processid; /* Process ID from fork() */ unsigned int childproccount = 0; /* Number of child processes */ if (argc!= 2) /* Test for correct number of arguments */ fprintf(stderr, "Usage: %s < Port>\n", argv[0]); exit(1); echoservport = atoi(argv[1]); /* First arg: local port */ servsock = CreateTCPSocket(echoServPort); for (;;) /* Run forever */ clntsock = AcceptTCPConnection(servSock); /* Fork child process and report any errors */ if ((processid = fork()) < 0) DieWithError("fork() failed"); else if (processid == 0) /* If this is the child process */ close(servsock); /* Child closes parent socket */ HandleTCP(clntSock); exit(0); /* Child process terminates */ printf("with child process: %d\n", (int) processid); close(clntsock); /* Parent closes child socket descriptor */ childproccount++; /* Increment number of outstanding child processes */ while (childproccount) /* Clean up all zombies */ processid = waitpid((pid_t) -1, NULL, WNOHANG); /* Non-blocking wait */ if (processid < 0) /* waitpid() error? */ DieWithError("waitpid() failed"); else if (processid == 0) /* No zombie to wait on */ break; else childproccount--; /* Cleaned up after a child */

#define MAXPENDING 5 /* Maximum outstanding connection requests */ void DieWithError(char *errormessage); /* Error handling function */ int CreateTCPSocket(unsigned short port) int sock; /* socket to create */ struct sockaddr_in echoservaddr; /* Local address */ /* Create socket for incoming connections */ if ((sock = socket(pf_inet, SOCK_STREAM, IPPROTO_TCP)) < 0) /* Construct local address structure */ memset(&echoservaddr, 0, sizeof(echoservaddr)); /* Zero out structure */ echoservaddr.sin_addr.s_addr = htonl(inaddr_any); /* Any incoming interface */ echoservaddr.sin_port = htons(port); /* Local port */ /* Bind to the local address */ if (bind(sock, (struct sockaddr *) &echoservaddr, sizeof(echoservaddr)) < 0) DieWithError("bind() failed"); #include <stdio.h> /* for printf() */ #include <sys/socket.h> /* for accept() */ #include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */ void DieWithError(char *errormessage); /* Error handling function */ int AcceptTCPConnection( int servsock ) int clntsock; /* Socket descriptor for client */ struct sockaddr_in echoclntaddr; /* address */ unsigned int clntlen; /* Length of client address data structure */ /* Set the size of the in-out parameter */ clntlen = sizeof(echoclntaddr); /* Wait for a client to connect */ if ((clntsock = accept(servsock, (struct sockaddr *) &echoclntaddr, &clntlen)) < 0) DieWithError("accept() failed"); /* clntsock is connected to a client! */ /* Mark the socket so it will listen for incoming connections */ if (listen(sock, MAXPENDING) < 0) DieWithError("listen() failed"); return sock; printf("handling client %s\n", inet_ntoa(echoclntaddr.sin_addr)); return clntsock; Resources/References! http://cs.ecs.baylor.edu/~donahoo/practical/c Sockets! http://www.ecst.csuchico.edu/~beej/guide! Network programming! Unix Interprocess communication