CSE 30264 Computer Networks

50
CSE 30264 Computer Networks Prof. Aaron Striegel Department of Computer Science & Engineering University of Notre Dame Lecture 3 – January 14, 2010

description

CSE 30264 Computer Networks. Prof. Aaron Striegel Department of Computer Science & Engineering University of Notre Dame Lecture 3 – January 14, 2010. Implementing Network Software. Outline Sockets Example Homework 2. Communication Paradigms. Stream Paradigm (TCP). Stream - PowerPoint PPT Presentation

Transcript of CSE 30264 Computer Networks

Page 1: CSE 30264 Computer Networks

CSE 30264

Computer Networks

Prof. Aaron StriegelDepartment of Computer Science & Engineering

University of Notre Dame

Lecture 3 – January 14, 2010

Page 2: CSE 30264 Computer Networks

Spring 2010 CSE 30264 2

Implementing Network Software

OutlineSocketsExampleHomework 2

Page 3: CSE 30264 Computer Networks

Communication Paradigms

Spring 2010 CSE 30264 3

Page 4: CSE 30264 Computer Networks

Stream Paradigm (TCP)• Stream

– Sequence of bytes flows from one application program to another

– Think of it like a tube of data• Bi-directional

– Streams in both directions– Client to server, server to client

• No boundaries– Streaming protocol does not

understand boundaries– Stream of bits

• No size limits*– One byte -> large blocks of data– * From the application perspective

• Protocol selects delivery size– Combine smaller blocks – Divide large blocks

Spring 2010 CSE 30264 4

IISfirefox

Port: 7583 Port: 80

129.74.200.5 129.74.120.75

IISfirefox

129.74.200.5, 7583 129.74.120.75, 80

Page 5: CSE 30264 Computer Networks

Message Paradigm (UDP)• Message paradigm

– Network accepts and delivers messages– Datagram service

• Messages are self-contained– Protocol simply forwards– No re-assembly, highly aware of packetization– N bytes in a message, N bytes

received on the other side– Size limit on messages

• May be uni-directional or bi-directional• Spray and pray – no guarantees

– May be lost– Delivered out-of-order– May be duplicated

• More burden on programmer

Spring 2010 CSE 30264 5

Shoutcast firefoxPort: 8000 Port: 42083

62.74.89.71 129.74.200.10

Shoutcast

Destination 129.74.200.10,

42083

Page 6: CSE 30264 Computer Networks

CSE 30264 6

OperatingSystem

Sockets

• Socket programming– Adapter that gets an app

onto the network– API – Application Programming

Interface– Give me a TCP socket,

hold the aggregation

Spring 2010

SocketNetwork

Stack

DeviceDrivers

PhysicalAdapter

Page 7: CSE 30264 Computer Networks

Spring 2010 CSE 30264 7

Socket Operations• Dependent on type of socket

– Different ops for TCP vs. UDP• Supported operations

– Specify local/remote communication endpoints• Who / where -> IP address / port

– Initiate a connection• Ring the telephone

– Wait for a connection• Server

– Send/receive data– Handle incoming data– Terminate connection gracefully– Handle connection termination from remote site– Abort communication– Handle error conditions or connection abort– Allocate and release local resources

Not to be confusedwith Sprockets

Page 8: CSE 30264 Computer Networks

Spring 2010 CSE 30264 8

Socket Communication

• Very similar to file I/O– File I/O– Open, close, read, write, seek, fcntl, ...

• Network communication– File descriptor for network comms

• Socket is just another file handle– Is a network connection really a file?

• Initiate, respond to aborted connection• Socket API was born

– Nominally the same between C and C++– Similar beyond C, C++

• Java, Perl, PHP, C#

Page 9: CSE 30264 Computer Networks

CSE 30264 9

Upcoming Programming

• Homework 2 - Implement a UDP client– Connect to a server– Send a message– Receive a message

• Project 1 – Implement Client / Server– Small scale TCP

• Google is your friend– Just document where you get help from– C UDP Socket Tutorial

Spring 2010

http://www.cs.ucsb.edu/~almeroth/classes/W01.176B/hw2/examples/udp-client.c

Page 10: CSE 30264 Computer Networks

Spring 2010 CSE 30264 10

Refresh -> Client-Server Model

• Server listens for requests from clients• Server: passive open• Client: active open• Example:

– file server– web server– print server– mail server– name server– X window server

SERVER

CLIENTS

request

response

Page 11: CSE 30264 Computer Networks

Spring 2010 CSE 30264 11

Overview - TCPSERVER

CLIENT

socket()

bind()

listen()

accept()

read()

write()

socket()

connect()

write()

read()

blocks until connection from clientconnection establishment

data request

data reply

process request

Page 12: CSE 30264 Computer Networks

Spring 2010 CSE 30264 12

Overview - UDP

socket()SERVER

CLIENT

socket()

sendto()recvfrom()

recvfrom()sendto()

data

data

Page 13: CSE 30264 Computer Networks

Spring 2009 CSE 30264 13

Socket Creation

int socket(int family, int type, int protocol);

• Return value: – Socket descriptor– Use for all subsequent operations

Page 14: CSE 30264 Computer Networks

CSE 30264 14

Socket Creation

Spring 2010

#include <sys/types.h>#include <sys/socket.h>

int s;

s = socket (PF_INET, SOCK_STREAM, 0);

Protocol Family – Internet

Socket Type – Streaming Socket

Default

Page 15: CSE 30264 Computer Networks

Spring 2010 CSE 30264 15

Socket Creation

• Family – PF_INET, PF_UNIX, ...– Also may be listed as AF_INET (Address Family)

• Socket Types– Datagram UDP SOCK_DGRAM– Reliable stream TCP SOCK_STREAM– Raw IP SOCK_RAW

• Must be root to use• Protocol

– Typically 0 = default protocol for type

Page 16: CSE 30264 Computer Networks

Spring 2010 CSE 30264 16

Endpoint Addresses

• Different protocols may have different representations.• TCP/IP uses combination of IP address and port.• Sockets offer different ‘address families’

– TCP/IP uses a single address representation (AF_INET).• PF_INET, AF_INET often confused

– Use same numeric value.– Most code

#define PF_INET AF_INET (Linux)

Two addressesBind for the local one

Connect to the remote one

Page 17: CSE 30264 Computer Networks

Spring 2010 CSE 30264 17

Socket Addressesstruct sockaddr { /* sys/socket.h */

sa_family_t sa_family; /* address family */char sa_data[14]; /* addressing information */

}

struct sockaddr_in {short sin_family; /* AF_INET */u_short sin_port; /* network byte order */struct sin_addr sin_addr; /* network address */

}

(2)

(1)

Two options (1) is most common, (2) is actually the recommended approach

Page 18: CSE 30264 Computer Networks

CSE 30264 18

Refresher - C

• Types – char, short, long• Pointers• size• struct• typecasting• Memset• Endian-ness

Spring 2010

See board in class / wiki for more examples

Page 19: CSE 30264 Computer Networks

Spring 2010 CSE 30264 19

Binding the Local Addressint bind(int s, struct sockaddr *addr, int addresslen);

• Socket has no notion of endpoint addresses when created– Neither local nor remote

• Necessary on the server side– Need to specify the local endpoint

• Not always necessary for the client– May just need to send data towards a destination– Let OS auto-assign

Page 20: CSE 30264 Computer Networks

Spring 2010 CSE 30264 20

Binding the Local Address#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>

int s;struct sockaddr_in sin;

s = socket(PF_INET, SOCK_DGRAM, 0);

memset((char *)&sin, 0, sizeof(sin));sin.sin_family = AF_INET;sin.sin_port = htons (6000); /* 0 -> let system choose */sin.sin_addr.s_addr = htonl(INADDR_ANY); /* allow any interface */

bind (s, (struct sockaddr *)&sin, sizeof(sin));

Page 21: CSE 30264 Computer Networks

CSE 30264 21

Breaking the Code Down

Spring 2010

memset((char *)&sin, 0, sizeof(sin));sin.sin_family = AF_INET;sin.sin_port = htons (6000); /* 0 -> let system choose */sin.sin_addr.s_addr = htonl(INADDR_ANY); /* allow any interface */

memset((char *)&sin, 0, sizeof(sin));sin.sin_family = AF_INET;sin.sin_port = htons (6000); /* 0 -> let system choose */sin.sin_addr.s_addr = htonl(INADDR_ANY); /* allow any interface */

Take the struct and initialize it to zeroes

Set the address family to Internet

Page 22: CSE 30264 Computer Networks

CSE 30264 22

Breaking the Code Down

Spring 2010

memset((char *)&sin, 0, sizeof(sin));sin.sin_family = AF_INET;sin.sin_port = htons (6000); sin.sin_addr.s_addr = htonl(INADDR_ANY);

memset((char *)&sin, 0, sizeof(sin));sin.sin_family = AF_INET;sin.sin_port = htons (6000); sin.sin_addr.s_addr = htonl(INADDR_ANY);

The port should be set to 6000

Just use a local address, I don’t care which one

htons – Host to network short

htonl – Host to network long

Page 23: CSE 30264 Computer Networks

CSE 30264 23

Converting a String

• What if we need to specify an address?– inet_addr(char *) – Takes a string with the dot notation, converts to a

four byte IPv4 value

Spring 2010

inet_addr(“129.74.56.5”)

inet_addr(argv[1])

Page 24: CSE 30264 Computer Networks

CSE 30264 24

Breaking the Code Down

Spring 2010

Bind our socket s to the information in the socket address structure sin and oh by the way, here is the size of that struct too

bind (s, (struct sockaddr *)&sin, sizeof(sin));

Typecast – oh yeah!

Page 25: CSE 30264 Computer Networks

CSE 30264 25

netstat• HW 1

– netstat –ra• Routing table

• Shows socket usage

Spring 2010

Page 26: CSE 30264 Computer Networks

Spring 2010 CSE 30264 26

setsockopt()/getsockopt()• May need to tweak the socket

– How long to wait to purge a socket?• Default is two MSL (Maximum Segment Lengths)• If not properly terminated, bind() will return EADDRINUSE.

setsockopt(int s, int level, int optname, const void *optval, int optlen);

getsockopt(int s, int level, int optname, void *optval, int *optlen);

• Before bind: setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));

• Allows re-use of port in use.

Page 27: CSE 30264 Computer Networks

CSE 30264 27

Why reuse ports?

• What if your code crashes?

• Otherwise, you wait … wait … wait … wait

• When we write servers, you will get a range of ports to use

• Rogue programs– ps –A –f

kill XXXX (XXXX is PID)

Spring 2010

Page 28: CSE 30264 Computer Networks

CSE 30264 28

What do we have so far?

• socket()– Creates the local “handle”– Identifier for all socket operations

• bind()– Allows us to pick the endpoint address

• Port number• Potentially address on a multi-interface machine

– Must be done on the server• setsocketopt, getsocketopt

– Change socket options

Spring 2010

Page 29: CSE 30264 Computer Networks

Spring 2010 CSE 30264 29

Contrast – TCP, UDPSERVER

CLIENT

socket()

bind()

listen()

accept()

read()

write()

socket()

connect()

write(), sendto()

read(), recvfrom()

blocks until connection from clientconnection establishment

data request

data reply

process request

TCP Only

TCP, UDP

Technically,it is possibleto use connectwith UDP

Page 30: CSE 30264 Computer Networks

Spring 2010 CSE 30264 30

Overview - UDP

socket()SERVER

CLIENT

socket()

sendto()recvfrom()

recvfrom()sendto()

data

data

Page 31: CSE 30264 Computer Networks

Spring 2010 CSE 30264 31

connect()

int connect(int s, struct sockaddr *addr, int namelen);

• Client issues connect() to– Establish remote address and port– Establish connection

• Fails if host not listening to port

Page 32: CSE 30264 Computer Networks

CSE 30264 32

Class Exercise

• Sketch the code for a connect call to the following location:

Spring 2010

IP Address: 192.168.4.6Port: 89

Page 33: CSE 30264 Computer Networks

CSE 30264 33

UDP – Send / Receive Data

• UDP -> Spray and Pray– sendto -> Send a message– recvfrom -> Listen on the port for a message

• Key parameters– Socket– Buffer pointer– Buffer size (bytes)– Socket address– Size of socket address struct

Spring 2010

Page 34: CSE 30264 Computer Networks

CSE 30264 34

recvfrom

Spring 2010

ssize_t recvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len);

SocketPointer to a pre-allocated bufferSize of the buffer (to avoid overflow)Flags (usually 0)Address struct – where the packet came fromLength of the address May be NULL

Page 35: CSE 30264 Computer Networks

CSE 30264 35

sendto

Spring 2010

ssize_t sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len);

SocketPointer to a pre-allocated bufferSize of the buffer (to avoid overflow)Flags (usually 0)Address struct – where the packet came fromLength of the address

Page 36: CSE 30264 Computer Networks

CSE 30264 36

In-Class Derivation

• Write a small snippet of code to send a packet via UDP

Spring 2010

Page 37: CSE 30264 Computer Networks

CSE 30264 37

Where next?

• UDP – protocol is up to programmer– How many messages?– Who talks when?– What type of message?

Spring 2010

Homework 2: Write a simple UDP client Read a small text file Send to the server Read / display the response

Page 38: CSE 30264 Computer Networks

Spring 2010 CSE 30264 38

Revisiting TCP – Server SideSERVER

CLIENT

socket()

bind()

listen()

accept()

read()

write()

socket()

connect()

write(), sendto()

read(), recvfrom()

blocks until connection from clientconnection establishment

data request

data reply

process request

TCP Only

TCP, UDP

Page 39: CSE 30264 Computer Networks

Spring 2010 CSE 30264 39

listen()

int listen(int s, int backlog);

• Only for stream sockets.• Socket being listened to can’t be used for client.• listen() does not wait for connections, but needed

to receive connection attempts.• Completes 3-way handshake.

Page 40: CSE 30264 Computer Networks

Spring 2010 CSE 30264 40

listen()

• Allows backlog pending connection requests (SYN, completed 3WH) while waiting for accept().

• Queue full: SYN requests are silently dropped.• “SYN-flood”: send fake TCP SYN requests to fill

queue.

Page 41: CSE 30264 Computer Networks

Spring 2010 CSE 30264 41

TCP Previewclient server

port=64444 port=9

SYN j

SYN k ACK j+1

ACK k+1

FIN

ACK

active openconnect()

(9, 64444)

active closeclose()

(64444, 9)listen()

(64444, 9)

Page 42: CSE 30264 Computer Networks

Spring 2010 CSE 30264 42

accept()

int accept(int s, struct sockaddr *addr, int *addrlen);

• By connection-oriented server, after listen().• Can’t preview connection: accept and close.• Returns a new socket.• Returns address of client.

Page 43: CSE 30264 Computer Networks

Spring 2010 CSE 30264 43

Sending/Receiving

• TCP– read/write: send/receive, no explicit address– send/recv: send/receive, flags

• UDP– sendto: specify destination explicitly– recvfrom: also receive address of peer– sendmsg: msghdr data structure, scatter/gather– recvmsg: msghdr data structure, scatter/gather

Page 44: CSE 30264 Computer Networks

Spring 2010 CSE 30264 44

Example: TCP Client#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>

int main(int argc, char *argv[]) { int s, n; struct sockaddr_in sin; char msg[80] = “Hello, World!”;

if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror(“socket”); return(-1); }

Page 45: CSE 30264 Computer Networks

Spring 2010 CSE 30264 45

Example: TCP Client sin.sin_family = AF_INET; sin.sin_port = htons(atoi(argv[2])); sin_addr.s_addr = inet_addr(argv[1]); if (connect(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) { perror(“connect”); return -1; } if (write(s, msg, strlen(msg)+1) < 0) { perror(“write”); return -1; } if ((n = read(s, msg, sizeof(msg))) < 0) { perror(“read”); return -1; } printf(“%d bytes: %s\n”, n, msg); if (close(s) < 0) { perror(“close”); return -1; } return 0;}

Page 46: CSE 30264 Computer Networks

Spring 2010 CSE 30264 46

Single-Threaded Server

int server;

server = initialize();while (1) { wait_for_request(server); read_request; send_answer;}

Page 47: CSE 30264 Computer Networks

Spring 2010 CSE 30264 47

Example: TCP Server

int main(int argc, char *argv[]) { int s, t, n; struct sockaddr_in sin; char *r; char buf[100]; int sinlen;

if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror(“socket); return -1; } sin.sin_family = AF_INET; sin.sin_port = htons(13333); sin.sin_addr.s_addr = INADDR_ANY; if (bind (s, (struct sockaddr *) &sin, sizeof(sin)) < 0) { perror(“bind”); return -1; } if (listen(s, 5) < 0) { perror(“listen”); return -1;}

Page 48: CSE 30264 Computer Networks

Spring 2010 CSE 30264 48

Example: TCP Server

for (;;) { sinlen = sizeof(sin); if ((t = accept(s, (struct sockaddr *) &sin, &sinlen)) < 0) { perror(“accept”); return -1; } if (read(t, &buf, 100) < 0) { perror (“read”); return -1;} r = gettime(); if (write(t, r, strlen(r)) < 0) { perror (“write”); return -1; } if (close(t) < 0) { perror(“close”); return -1; } } if (close(s) < 0) { perror(“close”); return -1; }}

Page 49: CSE 30264 Computer Networks

Other Socket Functions

• The socket API contains a variety of support functions– getpeername – gethostname– setsockopt – getsockopt – gethostbyname – gethostbyaddr

Spring 2010 CSE 30264 49

Page 50: CSE 30264 Computer Networks

What About Threaded Servers?• The socket API works well with concurrent servers • Implementations of the socket API adhere to the following inheritance

principle:– each new thread that is created inherits a copy of all open sockets from the

thread that created it– the socket implementation uses a reference count mechanism to control

each socket– when a socket is first created

• the system sets the socket’s reference count to 1• and the socket exists as long as the reference count remains positive.

– when a program creates an additional thread • the thread inherits a pointer to each open socket the program owns• and the system increments the reference count of each socket by 1

– when a thread calls close• the system decrements the reference count for the socket• if the reference count has reached zero, the socket is removed

Spring 2010 CSE 30264 50