Socket Programming in C/C++



Similar documents
ELEN 602: Computer Communications and Networking. Socket Programming Basics

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

The POSIX Socket API

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

Tutorial on Socket Programming

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

Socket Programming. Srinidhi Varadarajan

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

TCP/IP - Socket Programming

Network Programming with Sockets. Process Management in UNIX

NS3 Lab 1 TCP/IP Network Programming in C

Generalised Socket Addresses for Unix Squeak

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

UNIX Sockets. COS 461 Precept 1

Introduction to Socket programming using C

Lab 4: Socket Programming: netcat part

Unix Network Programming

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

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

Programmation Systèmes Cours 9 UNIX Domain Sockets

Application Architecture

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

BSD Sockets Interface Programmer s Guide

Chapter 3. Internet Applications and Network Programming

First Workshop on Open Source and Internet Technology for Scientific Environment: with case studies from Environmental Monitoring

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

Operating Systems Design 16. Networking: Sockets

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

Implementing and testing tftp

Network-Oriented Software Development. Course: CSc4360/CSc6360 Instructor: Dr. Beyah Sessions: M-W, 3:00 4:40pm Lecture 2

Writing a C-based Client/Server

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

Computer Networks Network architecture

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

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

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

Concurrent Server Design Alternatives

UNIX. Sockets. mgr inż. Marcin Borkowski

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

Network Programming with Sockets. Anatomy of an Internet Connection

Implementing Network Software

Network Programming TDC 561

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

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

Elementary Name and Address. Conversions

University of Amsterdam

TCP/IP Fundamentals. OSI Seven Layer Model & Seminar Outline

Ethernet. Ethernet. Network Devices

IP Network Layer. Datagram ID FLAG Fragment Offset. IP Datagrams. IP Addresses. IP Addresses. CSCE 515: Computer Network Programming TCP/IP

Unix System Administration

Division of Informatics, University of Edinburgh

Packet Sniffing and Spoofing Lab

Socket = an interface connection between two (dissimilar) pipes. OS provides this API to connect applications to networks. home.comcast.

Elementary Name and Address Conversions

Internet Protocol (IP) IP - Network Layer. IP Routing. Advantages of Connectionless. CSCE 515: Computer Network Programming IP routing

SSC - Communication and Networking Java Socket Programming (II)

Computer Networks. Chapter 5 Transport Protocols

Overview of Computer Networks

Chapter 11. User Datagram Protocol (UDP)

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

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.

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

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

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

Computer Networks - Xarxes de Computadors

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

Transport Layer. Chapter 3.4. Think about

IP - The Internet Protocol

CS 457 Lecture 19 Global Internet - BGP. Fall 2011

ICOM : Computer Networks Chapter 6: The Transport Layer. By Dr Yi Qian Department of Electronic and Computer Engineering Fall 2006 UPRM

Computer Networks & Security 2014/2015

Introduction to Computer Networks

Basic Networking Concepts. 1. Introduction 2. Protocols 3. Protocol Layers 4. Network Interconnection/Internet

sys socketcall: Network systems calls on Linux

NAT TCP SIP ALG Support

CSE 333 SECTION 6. Networking and sockets

IP addressing. Interface: Connection between host, router and physical link. IP address: 32-bit identifier for host, router interface

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

Lecture 28: Internet Protocols

Network Programming using sockets

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

q Connection establishment (if connection-oriented) q Data transfer q Connection release (if conn-oriented) q Addressing the transport user

Network Programming. Chapter The Client-Server Programming Model

Programming with TCP/IP Best Practices

Objectives of Lecture. Network Architecture. Protocols. Contents

Note! The problem set consists of two parts: Part I: The problem specifications pages Part II: The answer pages

Network Layers. CSC358 - Introduction to Computer Networks

Transport and Network Layer

Communications and Networking

DNS Domain Name System

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

Linux Kernel Architecture

Applications and Services. DNS (Domain Name System)

RARP: Reverse Address Resolution Protocol

How do I get to

Transcription:

September 24, 2004

Contact Info Mani Radhakrishnan Office 4224 SEL email mradhakr @ cs. uic. edu Office Hours Tuesday 1-4 PM

Introduction Sockets are a protocol independent method of creating a connection between processes. Sockets can be either connection based or connectionless: Is a connection established before communication or does each packet describe the destination? packet based or streams based: Are there message boundaries or is it one stream? reliable or unreliable. Can messages be lost, duplicated, reordered, or corrupted?

Socket characteristics Socket are characterized by their domain, type and transport protocol. Common domains are: AF UNIX: address format is UNIX pathname AF INET: address format is host and port number Common types are: virtual circuit: received in order transmitted and reliably datagram: arbitrary order, unreliable

Socket characteristics (cont d) Each socket type has one or more protocols. Ex: /IP (virtual circuits) (datagram) Use of sockets: Connection based sockets communicate client-server: the server waits for a connection from the client Connectionless sockets are peer-to-peer: each process is symmetric.

Socket APIs socket: creates a socket of a given domain, type, protocol (buy a phone) bind: assigns a name to the socket (get a telephone number) listen: specifies the number of pending connections that can be queued for a server socket. (call waiting allowance) accept: server accepts a connection request from a client (answer phone) connect: client requests a connection request to a server (call) send, sendto: write to connection (speak) recv, recvfrom: read from connection (listen) shutdown: end the call

Connection-based communication Server performs the following actions socket: create the socket bind: give the address of the socket on the server listen: specifies the maximum number of connection requests that can be pending for this process accept: establish the connection with a specific client send,recv: stream-based equivalents of read and write (repeated) shutdown: end reading or writing close: release kernel data structures

client Client performs the following actions socket: create the socket connect: connect to a server send,recv: (repeated) shutdown close

-based sockets server socket client socket bind connect listen accept close send/recv send/recv shutdown shutdown close close

socket API #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t s o c k e t ( i n t domain, i n t type, i n t p r o t o c o l ) ; Returns a file descriptor (called a socket ID) if successful, -1 otherwise. Note that the socket returns a socket descriptor which is the same as a file descriptor. The domain is AF INET. The type argument can be: SOCK STREAM: Establishes a virtual circuit for stream SOCK DGRAM: Establishes a datagram for communication SOCK SEQPACKET: Establishes a reliable, connection based, two way communication with maximum message size. (This is not available on most machines.) protocol is usually zero, so that type defines the connection within domain.

bind #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t b i n d ( i n t s i d, s t r u c t s o c k a d d r addrptr, i n t l e n ) Where sid: is the socket id addrptr: is a pointer to the address family dependent address structure len: is the size of *addrptr Associates a socket id with an address to which other processes can connect. In internet protocol the address is [ipnumber, portnumber]

sockaddr For the internet family: st r uc t s o c k a d d r i n { 2 s a f a m i l y t s i n f a m i l y ; // = AF INET i n p o r t t s i n p o r t ; // i s a p o r t number 4 s t r u c t i n a d d r s i n a d d r ; // an IP a d d r e s s } For unix sockets (only works between processes on the same machine) st r uc t s o c k a d d r u n { 2 u i n t 8 t s u n l e n g t h ; // s h o r t sun family ; // = AF LOCAL 4 char s u n p a t h [ 1 0 0 ] ; // n u l l t e r m i n a t e d pathname // (100 i s posix 1. g minimum ) 6 } When using internet sockets, the second parameter of bind (of type sockaddr in *) must be cast to (sockaddr *).

listen #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t l i s t e n ( i n t s i d, i n t s i z e ) ; Where size it the number of pending connection requests allowed (typically limited by Unix kernels to 5). Returns the 0 on success, or -1 if failure.

accept #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t a c c e p t ( i n t s i d, s t r u c t s o c k a d d r addrptr, i n t l e n P t r ) Returns the socketid and address of client connecting to socket. if lenptr or addrptr equal zero, no address structure is returned. lenptr is the maximum size of address structure that can be called, returns the actual value. Waits for an incoming request, and when received creates a socket for it.

accept styles There are basically three styles of using accept: Iterating server: Only one socket is opened at a time. When the processing on that connection is completed, the socket is closed, and next connection can be accepted. Forking server: After an accept, a child process is forked off to handle the connection. Variation: the child processes are preforked and are passed the socketid. Concurrent single server: use select to simultaneously wait on all open socketids, and waking up the process only when new data arrives.

Pro and Con of Accept styles Iterating server is basically a low performance technique since only one connection is open at a time. Forking servers enable using multiple processors. But they make sharing state difficult, unless performed with threads. Threads, however present a very fragile programming environment. Concurrent single server: reduces context switches relative to forking processes and complexity relative to threads. But does not benefit from multiprocessors.

send #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t send ( i n t s i d, c o n s t char b u f f e r P t r, i n t l e n, i n t f l a g ) Send a message. Returns the number of bytes sent or -1 if failure. (Must be a bound socket). flag is either 0: default MSG OOB: Out-of-band high priority communication

recv #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t r e c v ( i n t s i d, char b u f f e r P t r, i n t l e n, i n t f l a g s ) Receive up to len bytes in bufferptr. Returns the number of bytes received or -1 on failure. flags can be either 0: default MSG OOB: out-of-bound message MSG PEEK: look at message without removing

shutdown #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t shutdown ( i n t s i d, i n t how ) Disables sending (how=1 or how=2) or receiving (how=0 or how=2). Returns -1 on failure. acts as a partial close.

connect this is the first of the client calls #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t c o n n e c t ( i n t s i d, s t r u c t s o c k a d d r addrptr, i n t l e n ) Specifies the destination to form a connection with (addrptr), and returns a 0 if successful, -1 otherwise.

Denoting Connections Note that a connection is denoted by a 5-tuple: from IP from port protocol to IP to port So that multiple connections can share the same IP and port.

Port usage Note that the initiator of communications needs a fixed port to target communications. This means that some ports must be reserved for these well known ports. Port usage: 0-1023: These ports can only be binded to by root 1024-5000: well known ports 5001-64K-1: ephemeral ports

APIs for managing names and IP addresses We next consider a number of auxiliary APIs: The hostent structure: describes IP, hostname pairs gethostbyname: hostent of a specified machine htons, htonl, ntohs, ntohl: byte ordering inet pton, inet ntop: conversion of IP numbers between presentation and strings

gethostname 2 #i n c l u d e <unistd. h> i n t gethostname ( char hostname, s i z e t namelength ) Returns the hostname of the machine on which this command executes (What host am i?). Returns -1 on failure, 0 on success. MAXHOSTNAMELEN is defined in <sys/param.h>.

hostent structure s t r u c t h o s t e n t { 2 char h name ; // o f f i c i a l ( c a n o n i c a l ) name o f t h e h o s t char h a l i a s e s ; // n u l l t e r m i n a t e d a r r a y o f a l t e r n a t i v e hostnames 4 i n t h addrtype ; // host address type AF INET or AF INET6 i n t h l e n g t h ; // 4 o r 16 b y t e s 6 char h a d d r l i s t ; // IPv4 o r IPv6 l i s t o f a d d r e s s e s } Error is return through h error which can be: HOST NOT FOUND TRY AGAIN NO RECOVERY NO DATA

Gethostbyname Auxiliary functions 2 #i n c l u d e <netdb. h> st r uc t hostent gethostbyname ( const char hostname ) Translates a DNS name into a hostent. Example: st r uc t h o s t e n t h o s t E n t i t y = 2 gethostbyname ( b e r t. c s. u i c. edu ) ; memcpy ( socketaddr >sin addr, 4 h o s t E n t i t y >h a d d r l i s t [ 0 ], hostentity >h length ) ;

Network byte ordering Network ordering in big endian. (Sparc is big endian, Intel is little endian). // Host to network b y t e o r d e r f o r s h o r t s (16 b i t ) 2 u i n t 1 6 t h t o n s ( u i n t 1 6 t v ) ; 4 // Host to network byte order f o r long (32 b i t ) u i n t 3 2 t h t o n l ( u i n t 3 2 t v ) ; 6 // Network to host byte order f o r long (16 b i t ) 8 u i n t 1 6 t n t o h s ( u i n t 1 6 t v ) ; 10 // Network to host byte order f o r long (32 b i t ) u i n t 3 2 t n t o h l ( u i n t 3 2 t v ) ;

IP Number translation IP address strings to 32 bit number In what follows, p stands for presentation. Hence, these routines translate between the address as a string and the address as the number. Hence, we have 4 representations: IP number in host order IP number in network order Presentation (eg. dotted decimal) Fully qualified domain name Only the last needs an outside lookup to convert to one of the other formats.

inet pton #i n c l u d e <arpa / i n e t. h> 2 i n t i n e t p t o n ( i n t f a m i l y, c o n s t char s t r P t r, 4 v o i d addrptr ) ; returns 1 if OK, 0 if presentation error, -1 error Where family is either AF INET or AF INET6. The strptr is the IP address as a dotted string. Finally, addrptr points to either the 32 bit result (AF INET) or 128 bit result (AF INET6).

inet ntop #i n c l u d e <arpa / i n e t. h> 2 i n t i n e t n t o p ( i n t f a m i l y, c o n s t char addrptr, 4 char s t r P t r, s i z e t l e n ) ; returns 1 if OK, 0 if presentation error, -1 error Where family is either AF INET or AF INET6. The strptr is the return IP address as a dotted string. Finally, addrptr points to either the 32 bit (AF INET) or 128 bit (AF INET6). Length is the size of destination.

Example: /IP Server Code Without error checking. s o c k a d d r i n serveraddr ; 2 s o c k a d d r &s e r v e r A d d r C a s t = ( s o c k a d d r &) s e r v e r A d d r ; 4 // get a tcp / ip socket i n t l i s t e n F d = s o c k e t ( AF INET, SOCK STREAM, 0 ) ; 6 b z e r o (& s e r v e r A d d r, s i z e o f ( s e r v e r A d d r ) ) ; 8 s e r v e r A d d r. s i n f a m i l y = AF INET ; // any i n t e r n e t i n t e r f a c e on t h i s s e r v e r. 10 s e r v e r A d d r. s i n a d d r. s a d d r = h t o n l (INADDR ANY ) ; s e r v e r A d d r. s i n p o r t = h t o n s ( 1 3 ) ; 12 b i n d ( l i s t e n F d, &s e r v e r A d d r C a s t, s i z e o f ( s e r v e r A d d r ) ) ; 14 l i s t e n ( l i s t e n F d, 5 ) ; 16 f o r ( ; ; ) { 18 i n t connectfd = accept ( listenfd, ( sockaddr ) NULL, NULL ) ; 20 //.. r e a d and w r i t e o p e r a t i o n s on connectfd.. shutdown ( connectfd, 2 ) ; 22 c l o s e ( connectfd ) ; } Note that the above is an iterative server, which means that it serves one connection at a time.

Concurrent Server To build a concurrent server: a fork is performed after the accept. The child process closes listenfd, and communicates using connectfd. The parent process closses connectfd, and then loops back to the accept to wait for another connection request.

Example: /IP Client code s o c k a d d r i n serveraddr ; 2 s o c k a d d r &s e r v e r A d d r C a s t = ( s o c k a d d r &) s e r v e r A d d r ; 4 // get a tcp / ip socket i n t sockfd = socket ( AF INET, SOCK STREAM, 0 ) ; 6 b z e r o (& s e r v e r A d d r, s i z e o f ( s e r v e r A d d r ) ) ; 8 s e r v e r A d d r. s i n f a m i l y = AF INET ; // host IP # i n dotted d e c i m a l format! 10 i n e t p t o n ( AF INET, servername, s e r v e r A d d r. s i n a d d r ) ; s e r v e r A d d r. s i n p o r t = h t o n s ( 1 3 ) ; 12 c o n n e c t ( sockfd, s e r v e r A d d r C a s t, s i z e o f ( s e r v e r A d d r ) ) ; 14 //.. r e a d and w r i t e o p e r a t i o n s on sockfd.. shutdown ( sockfd, 2 ) ; 16 c l o s e ( sockfd ) ;

Connectionless communication Communication is symmetric (peer-to-peer) socket bind: bind is optional for initiator sendto, recvfrom (repeated) shutdown close

Connectionless communication client socket bind sendto/ recvfrom shutdown close

variations It is not necessary for both sockets to bind The receiver gets the address of the sender It is possible for a socket to connect In this case, send/recv (or write/read) must be used instead of sendto/recvfrom. Asynchronous errors can be returned (using ICMP)

sendto for connectionless protocols #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t sendto ( i n t sid, const void bufferptr, s i z e t b u f f e r L e n g t h, i n t f l a g, 6 s t r u c t s o c k a d d r addrptr, s o c k l e n t addrlength ) Send a buffer, bufferptr, of length bufferlength to address specified by addrptr of size addrlength. Returns number of bytes sent or -1 on error.

recvfrom for connectionless protocols #i n c l u d e <sys / types. h> 2 #i n c l u d e <sys / socket. h> 4 i n t recvfrom ( i n t sid, void bufferptr, i n t bufferlength, i n t flag, sockaddr addrptr, i n t addrlengthptr ) Receive a buffer in bufferptr of maximum length bufferlength from an unspecified sender. Sender address returned in addrptr, of size *addrlengthptr. Returns number of bytes receive or -1 on error.

Example: server i n t socketid = socket ( AF INET, SOCK DGRAM, 0 ) ; 2 sockaddr in serveraddr, clientaddr ; 4 s o c k a d d r &s e r v e r A d d r C a s t = ( s o c k a d d r &) s e r v e r A d d r ; s o c k a d d r &c l i e n t A d d r C a s t = ( s o c k a d d r &) c l i e n t A d d r ; 6 // a l l o w c o n n e c t i o n to any addr on h o s t 8 // f o r h o s t s w i t h m u l t i p l e network c o n n e c t i o n s // and a s t s e r v e r p o r t. 10 s e r v e r A d d r. s i n f a m i l y = AF INET ; s e r v e r A d d r. s i n p o r t = h t o n s ( s e r v e r P o r t ) ; 12 s e r v e r A d d r. s i n a d d r. s a d d r = INADDR ANY ; 14 // a s s o c i a t e p r o c e s s w i t h p o r t b i n d ( s o c k e t I d, &s e r v e r A d d r C a s t, s i z e o f ( addr ) ) ; 16 // r e c e i v e from a c l i e n t 18 i n t s i z e = s i z e o f ( c l i e n t A d d r ) ; r e c v f r o m ( s o c k e t I d, b u f f e r, b u f f e r S i z e, 20 0, c l i e n t A d d r C a s t, &s i z e ) ; 22 // r e p l y to t h e c l i e n t j u s t r e c e i v e d from s e n d t o ( s o c k e t I d, b u f f e r, b u f f e r S i z e, 24 0, c l i e n t A d d r C a s t, s i z e ) ; 26 c l o s e ( s o c k e t I d ) ;

Example: client i n t socketid = socket ( AF INET, SOCK DGRAM, 0 ) ; 2 sockaddr in serveraddr, clientaddr ; 4 s o c k a d d r &s e r v e r A d d r C a s t = ( s o c k a d d r &) s e r v e r A d d r ; s o c k a d d r &c l i e n t A d d r C a s t = ( s o c k a d d r &) c l i e n t A d d r ; 6 // s p e c i f y s e r v e r a d d r e s s, p o r t 8 s e r v e r A d d r. s i n f a m i l y = AF INET ; s e r v e r A d d r. s i n p o r t = h t o n s ( s e r v e r P o r t ) ; 10 st r uc t hostent hp = gethostbyname ( hostname ) ; memcpy ( ( char )& s e r v e r A d d r. s i n a d d r, 12 ( char )hp >h addr, hp >h length ) ; 14 // no need to bind i f not peer to peer i n t s i z e = s i z e o f ( s e r v e r A d d r ) ; 16 s e n d t o ( s o c k e t I d, b u f f e r, b u f f e r S i z e, 0, s e r v e r A d d r C a s t, s i z e ) ; 18 r e c v f r o m ( s o c k e t I d, b u f f e r, b u f f e r S i z e, 0, 20 s e r v e r A d d r C a s t, &s i z e ) ; 22 c l o s e ( s o c k e t I d ) ;