Socket Programming in C Slides Adapted on Jörn Altmann‘s Slides.

Slides:



Advertisements
Similar presentations
Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Advertisements

Sockets: Network IPC Internet Socket UNIX Domain Socket.
Introduction to Information Security Networking. Transmission Control Protocol (aka TCP) Most widely used protocol A TCP Connection is based on 6 crucial.
Socket Programming Application Programming Interface.
Elementary TCP Sockets Computer Networks Computer Networks Term B10 UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Quick Overview. 2 ISO/OSI Reference Model Application Application Presentation Presentation Session Session Transport Transport Network Network Data Link.
Socket Programming.
Socket Programming: a Primer Socket to me!. Feb. 23, 2001EE122, UCB2 Why does one need sockets? application network protocol sockets network.
EECS122 Communications Networks Socket Programming January 30th, 2003 Jörn Altmann.
1 Socket Interfaces Professor Jinhua Guo CIS527 Fall 2003.
Tutorial 8 Socket Programming
Katz, Stoica F04 EECS 122: Introduction to Computer Networks Sockets Programming Computer Science Division Department of Electrical Engineering and Computer.
EECS122 Communications Networks Socket Programming January 30th, 2003 Jörn Altmann.
Client Server Model The client machine (or the client process) makes the request for some resource or service, and the server machine (the server process)
EECC694 - Shaaban #1 lec #14 Spring The Application Layer Client/Server Computing, Basic Approaches: –Passing Messages. Example: Communication.
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
UNIX Sockets COS 461 Precept 1.
Introduction to Information Security Networking. Transmission Control Protocol (aka TCP) Most widely used protocol A ‘reliable’ (but not secure!) protocol.
Basic Socket Programming TCP/IP overview. TCP interface Reference: –UNIX Network Programming, by Richard Stevens. –UNIX man page.
ECE 4110 – Internetwork Programming Client-Server Model.
Sockets and intro to IO multiplexing. Goals We are going to study sockets programming as means to introduce IO multiplexing problem. We will revisit socket.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Zhu Reference: Daniel Spangenberger Computer Networks, Fall 2007 PPT-4 Socket Programming.
Chapter 17 Networking Dave Bremer Otago Polytechnic, N.Z. ©2008, Prentice Hall Operating Systems: Internals and Design Principles, 6/E William Stallings.
Computer Network Sritrusta Sukaridhoto. Computer Network – Sritrusta Sukaridhoto Why Computer Network ??? Stand alone Computer …. FOR WHAT ???
2: Application Layer 1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r Internet gaming r 2.3 FTP r 2.4 Electronic.
Sirak Kaewjamnong Computer Network Systems
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
 Wind River Systems, Inc Chapter - 13 Network Programming.
Computer Network Sritrusta Sukaridhoto. Why Computer Network ??? Stand alone Computer …. FOR WHAT ???
CPSC 441 TUTORIAL – FEB 13, 2012 TA: RUITNG ZHOU UDP REVIEW.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
TELE202 Lecture 15 Socket programming 1 Lecturer Dr Z. Huang Overview ¥Last Lecture »TCP/UDP (2) »Source: chapter 17 ¥This Lecture »Socket programming.
Elementary TCP Sockets UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
UNIX Sockets COS 461 Precept 1. Socket and Process Communication The interface that the OS provides to its networking subsystem application layer transport.
Introduction to Socket
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
1 Sockets Programming Socket to me!. 2 Network Application Programming Interface (API) The services provided by the operating system that provide the.
2: Application Layer 1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r Internet gaming r 2.3 FTP r 2.4 Electronic.
Socket Programming.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
Introduction to Sockets
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
2: Application Layer 1 Socket Programming UNIX Network Programming, Socket Programming Tutorial:
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
Lecture 15 Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
1 Network Communications A Brief Introduction. 2 Network Communications.
Socket Programming in C CS587x Lecture 3 Department of Computer Science Iowa State University.
1 Socket Interface. 2 Client-Server Architecture The client is the one who speaks first Typical client-server situations  Client and server on the same.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
SOCKET PROGRAMMING Presented By : Divya Sharma.
Introduction to Unix Network Programming
Introduction to Information Security
Socket Programming in C
Transport layer API: Socket Programming
Socket Programming in C
EE 122: Sockets Kevin Lai September 11, 2002.
Chapter 2: Application layer
Socket Programming(1/2)
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Internet Networking recitation #8
Outline Communications in Distributed Systems Socket Programming
Chapter 2: Application layer
Presentation transcript:

Socket Programming in C Slides Adapted on Jörn Altmann‘s Slides

CEN4500C2 Questions that will be Addressed What mechanisms are available for a programmer who writes network applications? How to write a network application that sends packets between hosts (client and server) across an IP network? Answer: socket API Client Server IP Network

CEN4500C3 Socket Programming Table of Contents 1. Network Application Programming Interface: Sockets and Internet Sockets Network Application Programming Interface 2. Network Programming Tips Network Programming Tips 3. Client-Server Architecture Client-Server Architecture 4. Example: Client Programming Example: Client Programming 5. Example: Server Programming Example: Server Programming 6. Network Programmer ’ s Mistakes Network Programmer ’ s Mistakes

CEN4500C4 Layers of the IP Protocol Suite Link Layer Transport Layer Network Layer Application Layer Link Layer Transport Layer Network Layer Application Layer Ethernet e.g. ftp e.g. TCP, UDP e.g. IP

CEN4500C5 Protocol Suite Location Internet Protocol Layer Link Layer Transport Layer (TCP, UDP) Network Layer (IP) Application Layer Network Card & Device Driver (e.g. Ethernet card) Operating System (e.g. Unix) Applications (e.g. browser, game, ftp) Application Programming Interface (API) (e.g. network API) Interface to the Network Card Location

CEN4500C6 Network API Operating system provides Application Programming Interface (API) for network application API is defined by a set of function types, data structures, and constants Desirable characteristics of the network interface Simple to use Flexible  independent from any application  allows program to use all functionality of the network Standardized  allows programmer to learn once, write anywhere Application Programming Interface for networks is called socket

CEN4500C7 Sockets Sockets provide mechanisms to communicate between computers across a network There are different kind of sockets DARPA Internet addresses (Internet Sockets) Unix interprocess communication (Unix Sockets) CCITT X.25 addresses and many others Berkeley sockets is the most popular Internet Socket runs on Linux, FreeBSD, OS X, Windows fed by the popularity of TCP/IP

CEN4500C8 Internet Sockets Support stream and datagram packets (e.g. TCP, UDP, IP) Is Similar to UNIX file I/O API ( provides a file descriptor) Based on C, single thread model does not require multiple threads

CEN4500C9 Types of Internet Sockets Different types of sockets implement different communication types (stream vs. datagram) Type of socket: stream socket connection-oriented two way communication reliable (error free), in order delivery can use the Transmission Control Protocol (TCP) e.g. telnet, ssh, http Type of socket: datagram socket connectionless, does not maintain an open connection, each packet is independent can use the User Datagram Protocol (UDP) e.g. IP telephony Other types exist: similar to the one above

CEN4500C10 Network Programming Tips Byte Ordering Naming Addressing

CEN4500C11 Byte Ordering of Integers Different CPU architectures have different byte ordering D3 high-order bytelow-order byte memory address A memory address A +1 Stored at little-endian computer Stored at big-endian computer low-order bytehigh-order byte F2 Integer representation (2 byte)

CEN4500C12 Message in Memory of of big-endian Computer Message is sent across Network C 4C 6F Byte Ordering Problem Question: What would happen if two computers with different integer byte ordering communicate? Message is: [Hello,1] Message is: [Hello,256] Processing C 4C 6F Message in Memory of little-endian Computer Processing Answer:  Nothing if they do not exchange integers!  But: If they exchange integers, they would get the wrong order of bytes, therefore, the wrong value! Example:

CEN4500C13 Byte Ordering Solution There are two solutions if computers with different byte ordering system want to communicate They must know the kind of architecture of the sending computer (bad solution, it has not been implemented) Introduction of a network byte order. The functions are: uint16_t htons(uint16_t host16bitvalue) uint32_t htonl(uint32_t host32bitvalue) uint16_t ntohs(uint16_t net16bitvalue) uint32_t ntohs(uint32_t net32bitvalue) Note: use for all integers (short and long), which are sent across the network Including port numbers and IP addresses

CEN4500C14 Network Programming Tips Byte Ordering Naming Addressing

CEN4500C15 Naming and Addressing Host name identifies a single host (see Domain Name System slides) variable length string (e.g. is mapped to one or more IP addresses IP Address written as dotted octets (e.g ) 32 bits. Not a number! But often needs to be converted to a 32-bit to use. Port number identifies a process on a host 16 bit number

CEN4500C16 Client-Server Architecture Client requests service from server Server responds with sending service or error message to client ClientServer request response

CEN4500C17 Simple Client-Server Example ClientServer request response socket() connect() send() recv() close() socket() bind() listen() accept() recv() send() recv() close() Connection establishment Data response Data request End-of-file notification

CEN4500C18 Example: Client Programming Create stream socket ( socket() ) Connect to server ( connect() ) While still connected: send message to server (send() ) receive (recv() ) data from server and process it Close TCP connection and Socket (close())

CEN4500C19 socket(): Initializing Socket Getting the file descriptor int chat_sock; if ((chat_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); printf("Failed to create socket\n"); abort (); } 1.parameter specifies protocol/address family 2.parameter specifies the socket type Other possibilities: SOCK_DGRAM 3.parameter specifies the protocol. 0 means protocol is chosen by the OS.

CEN4500C20 IP Address Data Structure struct sockaddr_in { short intsin_family; // Address family unsigned short intsin_port; // Port number struct in_addr sin_addr; // Internet address unsigned char sin_zero[8]; }; struct in_addr { unsigned long s_addr; // 4 bytes }; Padding of sin_zeros : struct sockaddr_in has same size as struct sockaddr

CEN4500C21 connect(): Making TCP Connection to Server struct sockaddr_in sin; struct hostent *host = gethostbyname (argv[1]); unsigned int server_address = *(unsigned long *) host->h_addr_list[0]; unsigned short server_port = atoi (argv[2]); memset (&sin, 0, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = server_address; sin.sin_port = htons (server_port); if (connect(chat_sock, (struct sockaddr *) &sin, sizeof (sin)) < 0) { perror("connect"); printf("Cannot connect to server\n"); abort(); }

CEN4500C22 send(): Sending Packets int send_packets(char *buffer, int buffer_len) { sent_bytes = send(chat_sock, buffer, buffer_len, 0); if (send_bytes < 0) { perror (“send"); } return 0; } Needs socket descriptor, Buffer containing the message, and Length of the message Can also use write()

CEN4500C23 Receiving Packets: Separating Data in a Stream Use records (data structures) to partition the data stream B Fixed length record 013 C D 5 A receive buffer slide through

CEN4500C24 Receiving Packets int receive_packets(char *buffer, int buffer_len, int *bytes_read) { int left = buffer_len - *bytes_read; received = recv(chat_sock, buffer + *bytes_read, left, 0); if (received < 0) { perror (“recv"); } if (received <= 0) { return close_connection(); } *bytes_read += received; while (*bytes_read > RECORD_LEN) { process_packet(buffer, RECORD_LEN); *bytes_read -= RECORD_LEN; memmove(buffer, buffer + RECORD_LEN, *bytes_read); } return 0; } Can also use read() buffer *bytes_read buffer_len

CEN4500C25 Server Programming: Simple Create stream socket ( socket() ) Bind port to socket ( bind() ) Listen for new client ( listen() ) While accept user connection and create a new socket (accept() ) data arrives from client (recv() ) data has to be send to client (send() )

CEN4500C26 bind(): Assign IP and Port struct sockaddr_in sin; struct hostent *host = gethostbyname (argv[1]); unsigned int server_address = *(unsigned long *) host->h_addr_list[0]; unsigned short server_port = atoi (argv[2]); memset (&sin, 0, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = server_address; sin.sin_port = htons (server_port); if (bind(chat_sock, (struct sockaddr *) &sin, sizeof (sin)) < 0) { perror("bind"); printf("Cannot bind server application to network\n"); abort(); }

CEN4500C27 bind(): bind() tells the OS to assign a local IP address and local port number to the socket. Many applications let the OS choose an IP address. Use wildcard INADDR_ANY as local address in this case. At server, user process must call bind() to assign a port At client, bind() is not required since OS may assign available port and IP address The server will get the port number of the client through the UDP/TCP packet header Note: Each application is represented by a server port number

CEN4500C28 listen(): Wait for Connections int listen(int sockfd, int backlog); Puts socket in a listening state, willing to handle incoming TCP connection request. Backlog: number of TCP connections that can be queued at the socket.

CEN4500C29 Server Example #define MYPORT 3490 // the port users will be connecting to #define BACKLOG 10 // how many pending connections queue will hold int main(void) { int sockfd, new_fd; // listen on sockfd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information int sin_size; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // auto. filled with local IP memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct

CEN4500C30 if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { // main accept() loop sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); if (send(new_fd, "Hello, world!\n", 14, 0) == -1) perror("send"); close(new_fd); } return 0; }

CEN4500C31 Client Example #include #define PORT 3490 // the port client will be connecting to #define MAXDATASIZE 100 // max number of bytes we can get // at once int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct hostent *he; struct sockaddr_in their_addr;// server's address information if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { // get the host info perror("gethostbyname"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); }

CEN4500C32 their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr); // already network byte order memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1){ perror("connect"); exit(1); } if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; printf("Received: %s",buf); close(sockfd); return 0; }

CEN4500C33 I/O Blocking socket() ; bind() ; listen(); while accept(); recv() ; send() ; Simple server has blocking problem Suppose 5 connections accepted. Suppose next accept() blocks. Other connections cannot send and receive. Cannot get keyboard input either.

CEN4500C34 select() :I/O Multiplexing waits on multiple file descriptors and timeout returns when any file descriptor is ready to be read or written or indicate an error, or timeout exceeded advantages simple application does not consume CPU cycles while waiting disadvantages does not scale to large number of file descriptors

CEN4500C35 Example: Server Programming create stream socket ( socket() ) Bind port to socket ( bind() ) Listen for new client ( listen() ) While Wait for (select() ) (depending on which file descriptors are ready) accept user connection and create a new socket (accept() ) data arrives from client (recv() ) data has to be send to client (send() )

CEN4500C36 Server: Alternative Ways of Handling Many Clients Forking a new process for each client: fork() But, creating new process is expensive. Multithreaded implementation: have one thread handling each client. Thread is like a process but light- weighted.

CEN4500C37 Network Programmer ’ s Mistakes byte ordering separating records in streams use of select() misinterpreting the project specification not knowing all available system calls

CEN4500C38 There are more System Calls Depends on communication type Datagram sockets use recvfrom() and sendto() for receiving and sending data Closing connection: close(), shutdown() Convenient functions (on UNIX) inet_aton, inet_ntoa inet_pton, inet_ntop

CEN4500C39 Literature short tutorial: Beej's Guide to Network Programming Unix Network Programming, volumes 1 and 2 by W. Richard Stevens. Published by Prentice Hall; ISBNs for volumes 1 and 2: X, Advanced Programming in the Unix Environment by W. Richard Stevens. Published by Addison Wesley. ISBN man pages on a Unix computer