Socket Programming Computer Networks, Spring 2010 Your TAs

Similar documents
Socket Programming. Kameswari Chebrolu Dept. of Electrical Engineering, IIT Kanpur

Tutorial on Socket Programming

Unix Network Programming

Introduction to Socket Programming Part I : TCP Clients, Servers; Host information

Socket Programming. Srinidhi Varadarajan

Lab 4: Socket Programming: netcat part

Network Programming with Sockets. Anatomy of an Internet Connection

Overview. Socket Programming. Using Ports to Identify Services. UNIX Socket API. Knowing What Port Number To Use. Socket: End Point of Communication

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab.

Porting applications & DNS issues. socket interface extensions for IPv6. Eva M. Castro. ecastro@dit.upm.es. dit. Porting applications & DNS issues UPM

Communication Networks. Introduction & Socket Programming Yuval Rochman

NS3 Lab 1 TCP/IP Network Programming in C

UNIX Sockets. COS 461 Precept 1

Implementing Network Software

Introduction to Socket programming using C

TCP/IP - Socket Programming

Socket Programming. Request. Reply. Figure 1. Client-Server paradigm

Socket Programming in C/C++

ELEN 602: Computer Communications and Networking. Socket Programming Basics

The POSIX Socket API

VMCI Sockets Programming Guide VMware ESX/ESXi 4.x VMware Workstation 7.x VMware Server 2.0

IT304 Experiment 2 To understand the concept of IPC, Pipes, Signals, Multi-Threading and Multiprocessing in the context of networking.

UNIX. Sockets. mgr inż. Marcin Borkowski

Programmation Systèmes Cours 9 UNIX Domain Sockets

Networks. Inter-process Communication. Pipes. Inter-process Communication

INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens

DESIGN AND IMPLEMENT AND ONLINE EXERCISE FOR TEACHING AND DEVELOPMENT OF A SERVER USING SOCKET PROGRAMMING IN C

CSE 333 SECTION 6. Networking and sockets

A Client-Server Transaction. Systemprogrammering 2006 Föreläsning 8 Network Programming. Hardware Org of a Network Host.

Lecture 17. Process Management. Process Management. Process Management. Inter-Process Communication. Inter-Process Communication

Concurrent Server Design Alternatives

Networks class CS144 Introduction to Computer Networking Goal: Teach the concepts underlying networks Prerequisites:

Hostnames. HOSTS.TXT was a bottleneck. Once there was HOSTS.TXT. CSCE515 Computer Network Programming. Hierarchical Organization of DNS

System calls. Problem: How to access resources other than CPU

Review of Previous Lecture

Computer Networks Network architecture

Client / Server Programming with TCP/IP Sockets

Elementary Name and Address Conversions

BSD Sockets Interface Programmer s Guide

Elementary Name and Address. Conversions

Lecture 7: Introduction to Sockets

KATRAGADDA INNOVATIVE TRUST FOR EDUCATION NETWORK PROGRAMMING. Notes prepared by D. Teja Santosh, Assistant Professor, KPES, Shabad, R.R. District.

Application Architecture

Windows Socket Programming & IPv6 Translation Middleware

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

A Client Server Transaction. Introduction to Computer Systems /18 243, fall th Lecture, Nov. 3 rd

Writing a C-based Client/Server

Direct Sockets. Christian Leber Lehrstuhl Rechnerarchitektur Universität Mannheim

Domain Name System (1)! gethostbyname (2)! gethostbyaddr (2)!

Giving credit where credit is due

Packet Sniffing and Spoofing Lab

Programming guidelines on transition to IPv6

Carnegie Mellon. Internetworking : Introduc0on to Computer Systems 19 th Lecture, Oct. 28, Instructors: Randy Bryant and Dave O Hallaron

IBM i Version 7.2. Programming Socket programming IBM

Network Programming with Sockets. Process Management in UNIX

This tutorial has been designed for everyone interested in learning the data exchange features of Unix Sockets.

Generalised Socket Addresses for Unix Squeak

Revision: 1.0 PROGRAMMER S GUIDE Date: Jul 1, 10. CrossCore XA. Programmer's guide.

SMTP-32 Library. Simple Mail Transfer Protocol Dynamic Link Library for Microsoft Windows. Version 5.2

RPG Does TCP/IP (Socket Progamming in RPG IV)

DNS Domain Name System

Operating Systems Design 16. Networking: Sockets

Writing Client/Server Programs in C Using Sockets (A Tutorial) Part I. Session Greg Granger grgran@sas. sas.com. SAS/C & C++ Support

Network Programming. Chapter The Client-Server Programming Model

Programming With Sockets 2

CS640: Computer Networks. Naming /ETC/HOSTS

Internetworking / : Introduc2on to Computer Systems 20 th Lecture, Nov. 6, 2012

Interprocess Communication Message Passing

Name and Address Conversions

Data Communication Networks. Lecture 1

How To Write On A Non-Blocking File On A Thumbtongue (Windows) (Windows 2) (Macintosh) (Amd64) (Apple) (Powerpoint) (Networking) (Unix) (Program) (

CHAPTER 7. ing with CGI

Project 1: Implement a simple hosts framework using UNIX TCP Sockets to demonstrate the concept of Mobile Agents

IPv6 Enabling CIFS/SMB Applications

TFTP Usage and Design. Diskless Workstation Booting 1. TFTP Usage and Design (cont.) CSCE 515: Computer Network Programming TFTP + Errors

CS 213, Fall 2000 Lab Assignment L5: Logging Web Proxy Assigned: Nov. 28, Due: Mon. Dec. 11, 11:59PM

Sockets Interface Java (C)

Hardware Prerequisites Atmel SAM W25 Xplained Pro Evaluation Kit Atmel IO1 extension Micro-USB Cable (Micro-A / Micro-B)

Porting and Deploying VoIP to IPv6: Lessons Learned

CS162 Operating Systems and Systems Programming Lecture 4. Introduction to I/O (Continued), Sockets, Networking. Recall: Fork and Wait

Goal: learn how to build client/server application that communicate using sockets. An interface between application and network

An Advanced 4.4BSD Interprocess Communication Tutorial

VMCI Sockets Programming Guide VMware ESXi 5.5 VMware Workstation 9.x

RIOT-Lab. How to use RIOT in the IoT-Lab. Oliver "Oleg" Hahm. November 7, 2014 INRIA. O. Hahm (INRIA) RIOT-Lab November 7, / 29

Network programming, DNS, and NAT. Copyright University of Illinois CS 241 Staff 1

Best practices in IPv6 enabled networking software development.

TCP/IP Sockets in C. Practical Guide for Programmers

System Calls and Standard I/O

15-441: Computer Networks Homework 1

RPC-based Toolkits RPC stub compilers automatically generate code to perform presentation layer conversions e.g., network byte-ordering and parameter

Implementing and testing tftp

What is CSG150 about? Fundamentals of Computer Networking. Course Outline. Lecture 1 Outline. Guevara Noubir noubir@ccs.neu.

University of Amsterdam

Introduction to Sockets Programming in C using TCP/IP. Professor: Panagiota Fatourou TA: Eleftherios Kosmas CSD - May 2012

Atomicity Strong need consistency 6

The exam has 110 possible points, 10 of which are extra credit. There is a Word Bank on Page 8. Pages 7-8 can be removed from the exam.

An Introductory 4.4BSD Interprocess Communication Tutorial

Software changes for Website and Application IPv6 Readiness

15-441: Computer Networks Project 1: Internet Relay Chat (IRC) Server

Programming with TCP/IP Best Practices

Transcription:

Socket Programming 15-441 Computer Networks, Spring 2010 Your TAs

Lecture Today MoCvaCon for sockets What s in a socket? Working with socket Concurrent network applicacons Project 1

Why Socket? How can I program a network applicacon? Share data Send messages Finish course projects... IPC - Interprocess CommunicaCon

IdenCfy the DesCnaCon Addressing IP address hostname (resolve to IP address via DNS) MulCplexing port Client socket address 128.2.194.242:3479 Server socket address 208.216.181.15:80 FTP Server ( 21 (port Client Client host address 128.2.194.242 Connection socket pair )128.2.194.242:3479, 208.216.181.15:80 ( HTTP Server ( 80 (port Server host address 208.216.181.15

Sockets How to use sockets Setup socket Where is the remote machine (IP address, hostname) What service gets the data (port) Send and Receive Designed just like any other I/O in unix send - - write recv - - read Close the socket

Overview Client Server socket socket open_clientfd connect Connection request bind listen accept open_listenfd Client / Server Session write read read write close EOF read close

Step 1 Setup Socket Both client and server need to setup the socket int socket(int domain, int type, int protocol); domain AF_INET - - IPv4 (AF_INET6 for IPv6) type SOCK_STREAM - - TCP SOCK_DGRAM - - UDP protocol 0 For example, int sockfd = socket(af_inet, SOCK_STREAM, 0);

Step 2 (Server) - Binding Only server need to bind int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen); sockfd file descriptor socket() returned my_addr struct sockaddr_in for IPv4 cast (struct sockaddr_in*) to (struct sockaddr*) struct sockaddr_in { short sin_family; // e.g. AF_INET ( htons(3490 unsigned short sin_port; // e.g. struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; struct in_addr { () inet_aton unsigned long s_addr; // load with };

What is that Cast? bind() takes in protocol- independent (struct sockaddr*) struct sockaddr { unsigned short char }; sa_family; // address family sa_data[14]; // protocol address C s polymorphism There are structs for IPv6, etc.

Step 2 (Server) - Binding contd. addrlen size of the sockaddr_in struct sockaddr_in saddr; int sockfd; unsigned short port = 80; if((sockfd=socket(af_inet, SOCK_STREAM, 0) < 0) { printf( Error creating socket\n );... } // from back a couple slides memset(&saddr, '\0', sizeof(saddr)); // zero structure out saddr.sin_family = AF_INET; // match the socket() call saddr.sin_addr.s_addr = htonl(inaddr_any); // bind to any local address saddr.sin_port = htons(port); // specify port to listen on if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf( Error binding\n );... }

What is htonl(), htons()? Byte ordering Network order is big- endian Host order can be big- or lidle- endian x86 is lidle- endian SPARC is big- endian Conversion htons(), htonl(): host to network short/long ntohs(), ntohl(): network order to host short/long What need to be converted? Addresses Port etc.

Step 3 (Server) - Listen Now we can listen int listen(int sockfd, int backlog); sockfd again, file descriptor socket() returned backlog number of pending conneccons to queue For example, listen(sockfd, 5);

Step 4 (Server) - Accept Server must explicitly accept incoming connec<ons int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) sockfd again... file descriptor socket() returned addr pointer to store client address, (struct sockaddr_in *) cast to (struct sockaddr *) addrlen pointer to store the returned size of addr, should be sizeof (*addr) For example int isock=accept(sockfd, (struct sockaddr_in *) &caddr, &clen);

Put Server Together struct sockaddr_in saddr, caddr; int sockfd, clen, isock; unsigned short port = 80; if((sockfd=socket(af_inet, SOCK_STREAM, 0) < 0) { printf( Error creating socket\n );... } // from back a couple slides memset(&saddr, '\0', sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(inaddr_any); saddr.sin_port = htons(port); // zero structure out // match the socket() call // bind to any local address // specify port to listen on if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf( Error binding\n );... } if(listen(sockfd, 5) < 0) { printf( Error listening\n );... } // listen for incoming connections ( clen=sizeof(caddr if((isock=accept(sockfd, (struct sockaddr *) &caddr, &clen)) < 0) { printf( Error accepting\n );... } // accept one

What about client? Client need not bind, listen, and accept All client need to do is to connect int connect(int sockfd, const struct sockaddr *saddr, socklen_t addrlen); For example, connect(sockfd, (struct sockaddr *) &saddr, sizeof (saddr));

Domain Name System (DNS) What if I want to send data to www.slashdot.org? DNS: Conceptually, DNS is a database colleccon of host entries struct hostent { char *h_name; // official hostname char **h_aliases; // vector of alternative hostnames int h_addrtype; // address type, e.g. AF_INET int h_length; // length of address in bytes, e.g. 4 for IPv4 char **h_addr_list; // vector of addresses char *h_addr; // first host address, synonym for h_addr_list[0] }; hostname - > IP address struct hostent *gethostbyname(const char *name); IP address - > hostname struct hostent *gethostbyaddr(const char *addr, int len, int type);

Put Client Together struct sockaddr_in saddr; struct hostent *h; int sockfd, connfd; unsigned short port = 80; if((sockfd=socket(af_inet, SOCK_STREAM, 0) < 0) { printf( Error creating socket\n );... } // from back a couple slides if((h=gethostbyname( www.slashdot.org )) == NULL) { // Lookup the hostname printf( Unknown host\n );... } memset(&saddr, '\0', sizeof(saddr)); // zero structure out saddr.sin_family = AF_INET; // match the socket() call memcpy((char *) &saddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); // copy the address saddr.sin_port = htons(port); // specify port to connect to if((connfd=connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // connect! printf( Cannot connect\n );... }

We Are Connected Server accepcng conneccons and client conneccng to servers Send and receive data ssize_t read(int fd, void *buf, size_t len); ssize_t write(int fd, const void *buf, size_t len); For example, read(sockfd, buffer, sizeof(buffer)); write(sockfd, hey\n, strlen( hey\n ));

TCP Framing TCP does NOT guarantee message boundaries IRC commands are terminated by a newline But you may not get one at the end of read(), e.g. One Send Hello\n MulCple Receives He, llo\n If you don t get the encre line from one read(), use a buffer

Revisited Client Server socket socket open_clientfd connect Connection request bind listen accept open_listenfd Client / Server Session write read read write close EOF read close

Close the Socket Don t forget to close the socket descriptor, like a file int close(int sockfd); Now server can loop around and accept a new conneccon when the old one finishes What s wrong here?

Server Flaw call connect client 1 server client 2 call accept ret connect call fgets User goes out to lunch Client 1 blocks waiting for user to type in data Server blocks waiting for data from Client 1 ret accept call read call connect Client 2 blocks waiting to complete its connection request until after lunch! Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides

Concurrent Servers client 1 server client 2 call connect ret connect call fgets User goes out to lunch Client 1 blocks waiting for user to type in data call accept ret accept ( block call read (don t call accept ret accept call read write close call connect ret connect call fgets write call read end read close Taken from D. Murray, R. Bryant, and G. Langale 15-441/213 slides

Concurrency Threading Easier to understand Race condicons increase complexity Select() Explicit control flows, no race condicons Explicit control more complicated There is no clear winner, but you MUST use select()

What is select()? Monitor mulcple descriptors How does it work? Setup sets of sockets to monitor select(): blocking uncl something happens Something could be Incoming conneccon: accept() Clients sending data: read() Pending data to send: write() Timeout

Concurrency Step 1 Allowing address reuse int sock, opts=1; sock = socket(...); // To give you an idea of where the new code goes setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opts, sizeof(opts)); Then we set the sockets to be non- blocking if((opts = fcntl(sock, F_GETFL)) < 0) { // Get current options printf( Error...\n );... } opts = (opts O_NONBLOCK); // Don't clobber your old settings if(fcntl(sock, F_SETFL, opts) < 0) { printf( Error...\n );... } bind(...); // To again give you an idea where the new code goes

Concurrency Step 2 Monitor sockets with select() int select(int maxfd, fd_set *readfds, fd_set *writefds, fd_set *excepuds, const struct Vmespec *Vmeout); maxfd max file descriptor + 1 fd_set: bit vector with FD_SETSIZE bits readfds: bit vector of read descriptors to monitor writefds: bit vector of write descriptors to monitor excepuds: set to NULL Vmeout how long to wait without accvity before returning

What about bit vectors? void FD_ZERO(fd_set *fdset); clear out all bits void FD_SET(int fd, fd_set *fdset); set one bit void FD_CLR(int fd, fd_set *fdset); clear one bit int FD_ISSET(int fd, fd_set *fdset); test whether fd bit is set

The Server // socket() call and non-blocking code is above this point if((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { // bind! printf( Error binding\n );... } if(listen(sockfd, 5) < 0) { printf( Error listening\n );... } // listen for incoming connections clen=sizeof(caddr); // Setup pool.read_set with an FD_ZERO() and FD_SET() for ( returned // your server socket file descriptor. (whatever socket() while(1) { pool.ready_set = pool.read_set; // Save the current state pool.nready = select(pool.maxfd+1, &pool.ready_set, &pool.write_set, NULL, NULL); if(fd_isset(sockfd, &pool.ready_set)) { // Check if there is an incoming conn isock=accept(sockfd, (struct sockaddr *) &caddr, &clen); // accept it add_client(isock, &pool); // add the client by the incoming socket fd } } check_clients(&pool); // check if any data needs to be sent/received from clients... close(sockfd);

What is pool? typedef struct { /* represents a pool of connected descriptors */ int maxfd; /* largest descriptor in read_set */ fd_set read_set; /* set of all active read descriptors */ fd_set write_set; /* set of all active read descriptors */ fd_set ready_set; /* subset of descriptors ready for reading */ int nready; /* number of ready descriptors from select */ int maxi; /* highwater index into client array */ int clientfd[fd_setsize]; /* set of active descriptors */ rio_t clientrio[fd_setsize]; /* set of active read buffers */... // ADD WHAT WOULD BE HELPFUL FOR PROJECT1 } pool;

What about checking clients? The main loop only tests for incoming conneccons There are other reasons the server wakes up Clients are sending data, pending data to write to buffer, clients closing conneccons, etc. Store all client file descriptors in pool Keep the while(1) loop thin Delegate to funccons Come up with your own design

Summary Sockets socket setup I/O close Client: socket()- - - - - - - - - - - - - - - - - - - - - - - >connect()- >I/O- >close() Server: socket()- >bind()- >listen()- >accept()- - - >I/O- >close() DNS gethostbyname() Concurrency select() Bit vector operacons fd_set, FD_ZERO(), FD_SET(), FD_CLR(), FD_ISSET()

About Project 1 Standalone IRC server Checkpoint 1: subversion and Makefile Check in a Makefile and source code Makefile can build executable named sircd No server funccons necessary Checkpoint 2: echo server Use select() to handle mulcple clients

SuggesCons Start early! Work ahead of checkpoints Read the man pages Email Kaushik (kaushik AT cs DOT cmu DOT edu) if you didn t get a svn username and password

Reference for Socket Programming hdp://www.lowtek.com/sockets/ Feel free to share your reference on the bboard!