16
1 Computer Networks LECTURE 2 Performance and Socket Programming Sandhya Dwarkadas Department of Computer Science University of Rochester Computer Networking Definition: Provides the means for a diverse set of applications distributed over connected computers to communicate arbitrary data between them Course goal: Understand how networks are implemented Reality: Networks are evolving incredibly fast Therefore: We will study the concepts and principles of networking rather than standards and existing protocols develop intuition Assignments Lab1 playing with packet sniffing DUE: TODAY Lab 2 socket programming DUE: Wednesday September 14 th Introduction What is the Internet? A nuts and boltsview billions of connected computing devices: hosts = end systems running network apps communication links fiber, copper, radio, satellite transmission rate: bandwidth packet switches: forward packets (chunks of data) routers and switches wired links wireless links router smartphone PC server wireless laptop 1-4 mobile network global ISP regional ISP home network institutional network

Computer Networks LECTURE 2 Performance and Socket …Computer Networks LECTURE 2 Performance and Socket Programming Sandhya Dwarkadas Department of Computer Science University of

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

1

Computer Networks

LECTURE 2

Performance and Socket

Programming

Sandhya Dwarkadas

Department of Computer Science

University of Rochester

Computer Networking• Definition: Provides the means for a diverse set of

applications distributed over connected computers

to communicate arbitrary data between them

• Course goal: Understand how networks are

implemented

• Reality: Networks are evolving incredibly fast

• Therefore:

– We will study the concepts and principles of

networking rather than standards and existing protocols

– develop intuition

Assignments

• Lab1 – playing with packet sniffing

– DUE: TODAY

• Lab 2 – socket programming

– DUE: Wednesday September 14th

Introduction

What is the Internet?

A “nuts and bolts” view

• billions of connected

computing devices:

– hosts = end systems

– running network apps communication links

• fiber, copper, radio, satellite

• transmission rate: bandwidth

packet switches: forward packets (chunks of data)

• routers and switches

wiredlinks

wirelesslinks

router

smartphone

PC

server

wirelesslaptop

1-4

mobile network

global ISP

regional ISP

home network

institutionalnetwork

2

Introduction

• mesh of

interconnected routers

• packet-switching:

hosts break

application-layer

messages into packets

– forward packets from

one router to the next,

across links on path

from source to

destination

– each packet

transmitted at full link

capacity

The network core

1-5

PERFORMANCE

CONSIDERATIONS

Traceroute cs.rice.edu

• traceroute to cs.rice.edu (128.42.128.17), 30 hops max, 60 byte packets

• 1 ur-net-gw2.cs.rochester.edu (128.151.67.100) 0.608 ms 0.689 ms 0.860 ms

• 2 cs-bbgw-if.utd.rochester.edu (128.151.65.250) 1.207 ms 1.247 ms 1.344 ms

• 3 cat6509-urmc-sb-c.net.rochester.edu (128.151.254.149) 1.503 ms 1.628 ms 1.765 ms

• 4 vl510.upns.net.rochester.edu (128.151.254.2) 2.318 ms 2.446 ms 2.506 ms

• 5 vl512.ir01.sb.mcm.net.rochester.edu (128.151.254.14) 2.893 ms 2.947 ms 3.059 ms

• 6 vl948.ir01.sw.mca.net.rochester.edu (128.151.254.142) 3.685 ms 3.230 ms 3.252 ms

• 7 roc-7600-uofr.nysernet.net (199.109.10.5) 2.964 ms 2.716 ms 2.704 ms

• 8 buf-7600-roc-7600.nysernet.net (199.109.7.1) 4.294 ms 4.209 ms 4.178 ms

• 9 I2-CHIC-buf-9208.nysernet.net (199.109.11.38) 18.068 ms 17.505 ms 17.510 ms

• 10 et-7-1-0.4070.rtsw.kans.net.internet2.edu (198.71.45.15) 34.983 ms 34.662 ms 34.701 ms

• 11 74.200.187.54 (74.200.187.54) 65.389 ms 64.729 ms 64.694 ms

• 12 74.200.187.46 (74.200.187.46) 49.537 ms 49.410 ms 49.408 ms

• 13 * rice-i2-1.setg.net (198.32.229.138) 48.276 ms 48.271 ms

• 14 * * *

• 15 * * *

• 16 bianca.cs.rice.edu (128.42.128.17) 49.681 ms !X 49.292 ms !X 49.240 ms !X

traceroute cs.stanford.edu• traceroute to cs.stanford.edu (171.64.64.64), 30 hops max, 60 byte packets

• 1 ur-net-gw2.cs.rochester.edu (128.151.67.100) 0.662 ms 0.710 ms 0.818 ms

• 2 cs-bbgw-if.utd.rochester.edu (128.151.65.250) 1.424 ms 1.451 ms 1.477 ms

• 3 cat6509-urmc-sb-c.net.rochester.edu (128.151.254.149) 1.548 ms 1.640 ms 1.699 ms

• 4 vl510.upns.net.rochester.edu (128.151.254.2) 2.222 ms 2.283 ms 2.335 ms

• 5 vl512.ir01.sb.mcm.net.rochester.edu (128.151.254.14) 2.689 ms 2.816 ms 3.045 ms

• 6 vl948.ir01.sw.mca.net.rochester.edu (128.151.254.142) 3.172 ms 2.067 ms 1.478 ms

• 7 roc-7600-uofr.nysernet.net (199.109.10.5) 1.627 ms 1.677 ms 1.239 ms

• 8 buf-7600-roc-7600.nysernet.net (199.109.7.1) 2.788 ms 2.857 ms 2.901 ms

• 9 I2-CHIC-buf-9208.nysernet.net (199.109.11.38) 18.347 ms 17.136 ms 17.128 ms

• 10 et-7-1-0.4070.rtsw.kans.net.internet2.edu (198.71.45.15) 34.289 ms 34.314 ms 34.385 ms

• 11 et-1-0-0.109.rtr.hous.net.internet2.edu (198.71.45.16) 49.132 ms 49.203 ms 49.197 ms

• 12 et-7-1-0.4070.rtsw.losa.net.internet2.edu (198.71.45.21) 81.640 ms 81.612 ms 81.733 ms

• 13 137.164.26.200 (137.164.26.200) 82.005 ms 82.007 ms 82.189 ms

• 14 hpr-svl-hpr3--lax-hpr3-100ge.cenic.net (137.164.25.74) 89.108 ms 87.579 ms 87.723 ms

• 15 hpr-stan-ge--svl-hpr2.cenic.net (137.164.27.162) 90.029 ms 88.132 ms 88.119 ms

• 16 csmx-west-rtr-vl8.SUNet (171.64.255.214) 90.352 ms 90.295 ms 90.301 ms

• 17 CS.stanford.edu (171.64.64.64) 88.560 ms 88.571 ms 88.668 ms

3

traceroute to cs.rochester.edu,

ece.rochester.edutraceroute to cs.rochester.edu (192.5.53.208), 30 hops max, 60 byte

packets

• 1 ur-net-gw2.cs.rochester.edu (128.151.67.100) 0.276 ms 0.297 ms

0.354 ms

• 2 anon.cs.rochester.edu (192.5.53.208) 0.179 ms 0.182 ms 0.177 ms

traceroute to ece.rochester.edu (128.151.160.11), 30 hops max, 60 byte

packets

• 1 ur-net-gw2.cs.rochester.edu (128.151.67.100) 0.666 ms 0.740 ms

0.918 ms

• 2 * * *

• 3 valhalla.ee.rochester.edu (128.151.160.11) 2.119 ms 2.158 ms

2.391 msIntroduction

Packet-switching: store-and-forward

• takes L/R seconds to transmit (push

out) L-bit packet into link at R bps

• store and forward: entire packet

must arrive at router before it can

be transmitted on next link

one-hop numerical example:

L = 7.5 Mbits

R = 1.5 Mbps

one-hop transmission delay = 5 sec

1-10

sourceR bps

destination123

L bitsper packet

R bps

end-end delay = 2L/R (assuming zero propagation delay)

Introduction

Packet Switching: queueing delay, loss

A

B

CR = 100 Mb/s

R = 1.5 Mb/sD

Equeue of packetswaiting for output link

1-11

queuing and loss: if arrival rate (in bits) to link exceeds transmission rate of link

for a period of time:

• packets will queue, wait to be transmitted on link

• packets can be dropped (lost) if memory (buffer) fills up

Introduction

Alternative core: circuit switching

end-end resources

allocated to, reserved

for “call” between

source & dest:• in diagram, each link has four

circuits.

– call gets 2nd circuit in top

link and 1st circuit in

right link.

• dedicated resources: no sharing

– circuit-like (guaranteed)

performance

• circuit segment idle if not used

by call (no sharing)

• commonly used in traditional

telephone networks

1-12

4

Introduction

Circuit switching: FDM versus TDM

FDM

frequency

timeTDM

frequency

time

4 users

Example:

1-13 Introduction

Packet switching versus circuit switching

example:

• 1 Mb/s link

• each user:

• 100 kb/s when “active”

• active 10% of time

• circuit-switching:

– 10 users

• packet switching:

– with 35 users, probability >

10 active at same time is less

than .0004 *

packet switching allows more users to use network!

Nusers

1 Mbps link

Q: how did we get value 0.0004?

Q: what happens if > 35 users ?

1-14* Check out the online interactive exercises for more examples: http://gaia.cs.umass.edu/kurose_ross/interactive/

Introduction

• great for bursty data

– resource sharing

– simpler, no call setup

• excessive congestion possible: packet delay and loss

– protocols needed for reliable data transfer,

congestion control

• Q: How to provide circuit-like behavior?

– bandwidth guarantees needed for audio/video apps

– still an unsolved problem (chapter 7)

is packet switching a “slam dunk winner?”

Packet switching versus circuit switching

1-15

A

B

Introduction

How do loss and delay occur?

packets queue in router buffers packet arrival rate to link (temporarily) exceeds output link

capacity

packets queue, wait for turnpacket being transmitted (delay)

packets queueing (delay)

free (available) buffers: arriving packets

dropped (loss) if no free buffers

1-16

5

Introduction

Four sources of packet delay

dproc: nodal

processing check bit errors

determine output link

typically < msec

dqueue: queueing delay time waiting at output link

for transmission

depends on congestion level of router

1-17

propagation

nodal

processing queueing

dnodal = dproc + dqueue + dtrans + dprop

A

B

transmission

Introduction

dtrans: transmission delay: L: packet length (bits)

R: link bandwidth (bps)

dtrans = L/R

dprop: propagation delay: d: length of physical link

s: propagation speed (~2x108 m/sec)

dprop = d/s

Four sources of packet delay

1-18* Check out the Java applet for an interactive animation on trans vs. prop delay

dtrans and dprop

very different

* Check out the online interactive exercises for more examples: http://gaia.cs.umass.edu/kurose_ross/interactive/

propagation

nodal

processing queueing

dnodal = dproc + dqueue + dtrans + dprop

A

B

transmission

Introduction

Caravan analogy

• cars “propagate” at

100 km/hr

• toll booth takes 12 sec to

service car (bit transmission

time)

• car ~ bit; caravan ~ packet

• Q: How long until caravan is

lined up before 2nd toll

booth?

• time to “push” entire

caravan through toll

booth onto highway =

12*10 = 120 sec

• time for last car to

propagate from 1st to

2nd toll both:

100km/(100km/hr)= 1 hr

• A: 62 minutes

toll

booth

toll

booth

ten-car

caravan

100 km 100 km

1-19 Introduction

Caravan analogy (more)

• suppose cars now “propagate” at 1000 km/hr

• and suppose toll booth now takes one min to service a car

• Q: Will cars arrive to 2nd booth before all cars serviced at first

booth?

• A: Yes! after 7 min, first car arrives at second booth; three

cars still at first booth

toll

booth

toll

booth

ten-car

caravan

100 km 100 km

1-20

6

Introduction

• R: link bandwidth (bps)

• L: packet length (bits)

• a: average packet arrival

ratetraffic intensity

= La/R

La/R ~ 0: avg. queueing delay small

La/R -> 1: avg. queueing delay large

La/R > 1: more “work” arriving

than can be serviced, average delay infinite!

avera

ge queuein

g

dela

y

La/R ~ 0

La/R -> 11-21

Queueing delay (revisited)

Introduction

“Real” Internet delays and routes

• what do “real” Internet delay & loss look

like?

• traceroute program: provides delay

measurement from source to router along

end-end Internet path towards destination.

For all i:

– sends three packets that will reach router i on

path towards destination

– router i will return packets to sender

– sender times interval between transmission and

reply.

3 probes

3 probes

3 probes

1-22

Introduction

“Real” Internet delays, routes

1 cs-gw (128.119.240.254) 1 ms 1 ms 2 ms2 border1-rt-fa5-1-0.gw.umass.edu (128.119.3.145) 1 ms 1 ms 2 ms3 cht-vbns.gw.umass.edu (128.119.3.130) 6 ms 5 ms 5 ms4 jn1-at1-0-0-19.wor.vbns.net (204.147.132.129) 16 ms 11 ms 13 ms 5 jn1-so7-0-0-0.wae.vbns.net (204.147.136.136) 21 ms 18 ms 18 ms 6 abilene-vbns.abilene.ucaid.edu (198.32.11.9) 22 ms 18 ms 22 ms7 nycm-wash.abilene.ucaid.edu (198.32.8.46) 22 ms 22 ms 22 ms8 62.40.103.253 (62.40.103.253) 104 ms 109 ms 106 ms9 de2-1.de1.de.geant.net (62.40.96.129) 109 ms 102 ms 104 ms10 de.fr1.fr.geant.net (62.40.96.50) 113 ms 121 ms 114 ms11 renater-gw.fr1.fr.geant.net (62.40.103.54) 112 ms 114 ms 112 ms12 nio-n2.cssi.renater.fr (193.51.206.13) 111 ms 114 ms 116 ms13 nice.cssi.renater.fr (195.220.98.102) 123 ms 125 ms 124 ms14 r3t2-nice.cssi.renater.fr (195.220.98.110) 126 ms 126 ms 124 ms15 eurecom-valbonne.r3t2.ft.net (193.48.50.54) 135 ms 128 ms 133 ms16 194.214.211.25 (194.214.211.25) 126 ms 128 ms 126 ms17 * * *18 * * *

19 fantasia.eurecom.fr (193.55.113.142) 132 ms 128 ms 136 ms

traceroute: gaia.cs.umass.edu to www.eurecom.fr

3 delay measurements from

gaia.cs.umass.edu to cs-gw.cs.umass.edu

* means no response (probe lost, router not replying)

trans-oceanic

link

1-23* Do some traceroutes from exotic countries at www.traceroute.org

Introduction

Packet loss

• queue (aka buffer) preceding link in buffer has

finite capacity

• packet arriving to full queue dropped (aka lost)

• lost packet may be retransmitted by previous

node, by source end system, or not at all

A

B

packet being transmitted

packet arriving to

full buffer is lost

buffer

(waiting area)

1-24

7

Introduction

Throughput

• throughput: rate (bits/time unit) at which

bits transferred between sender/receiver

– instantaneous: rate at given point in time

– average: rate over longer period of time

server, withfile of F bits

to send to client

link capacityRs bits/sec

link capacityRc bits/sec

server sends bits (fluid) into pipe

pipe that can carryfluid at rateRs bits/sec)

pipe that can carryfluid at rateRc bits/sec)

1-25 Introduction

Throughput (more)

• Rs < Rc What is average end-end throughput?

Rs bits/sec Rc bits/sec

Rs > Rc What is average end-end throughput?

link on end-end path that constrains end-end throughput

bottleneck link

Rs bits/sec Rc bits/sec

1-26

Introduction

Throughput: Internet scenario

10 connections (fairly) share

backbone bottleneck link R bits/sec

Rs

Rs

Rs

Rc

Rc

Rc

R

• per-connection

end-end

throughput:

min(Rc,Rs,R/10)

• in practice: Rc or

Rs is often

bottleneck

1-27* Check out the online interactive exercises for more

examples: http://gaia.cs.umass.edu/kurose_ross/interactive/

Introduction

Packet-switching: store-and-forward

• takes L/R seconds to transmit (push

out) L-bit packet into link at R bps

• store and forward: entire packet

must arrive at router before it can

be transmitted on next link

one-hop numerical example:

L = 7.5 Mbits

R = 1.5 Mbps

one-hop transmission delay = 5 sec

1-28

sourceR bps

destination123

L bitsper packet

R bps

end-end delay = 2L/R (assuming zero propagation delay)

8

Introduction

Packet Switching: queueing delay, loss

A

B

CR = 100 Mb/s

R = 1.5 Mb/sD

Equeue of packetswaiting for output link

1-29

queuing and loss: if arrival rate (in bits) to link exceeds transmission rate of link

for a period of time:

• packets will queue, wait to be transmitted on link

• packets can be dropped (lost) if memory (buffer) fills up

NETWORK INTERFACE: HOW DOES THE HOST CONNECT TO THE

COMMUNICATION LINK?

Abstract View of Machine

Network Interface Card (NIC)

Network Interface Card (NIC)

• Network essentially an I/O device through which

data is sent/received

• NIC contains signaling and control logic to send

bits down the wire (or wireless …)

• NIC-operating system (OS) interaction through

– Polling (of the device control status register)

– Interrupts

• Device driver – software that manipulates NIC

(usually part of OS)

9

How to get data into/out of

memory?

• Direct Memory Access (DMA)

• Programmed I/O

How to protect network access?

• Memory map so that only privileged code can

access page

• Use special I/O instructions that are privileged

Typical actions: user requests packet to be sent, OS

copies data into kernel space, device driver copies

data into the network adaptor, and vice versa

PROTOCOL/ABSTRACTION

LAYERS

Introduction

What’s a protocol?

human protocols:

• “what’s the time?”

• “I have a question”

• introductions

… specific messages sent

… specific actions taken

when messages

received, or other events

network protocols: machines rather than

humans

all communication activity

in Internet governed by

protocols

protocols define format, order of

messages sent and received

among network entities, and

actions taken on message

transmission, receipt1-35

Computer Networks: Principles

and Architecture

• Network Architecture:

– Design and Implementation Guide

Principle of Abstraction – layering of protocols

A protocol provides a communication service to

the next higher-level layer

• Service interface – e.g., send and receive

• Peer interface – form and meaning of messages

exchanged between peers

10

Introduction

a human protocol and a computer network

protocol:

Q: other human protocols?

Hi

Hi

Got the

time?

2:00

TCP connectionresponse

Get http://www.awl.com/kurose-ross

<file>

time

TCP connectionrequest

What’s a protocol?

1-37 Introduction

Protocol “layers”

Networks are complex,

with many “pieces”:

hosts

routers

links of various

media

applications

protocols

hardware,

software

Question:

is there any hope of

organizing structure

of network?

…. or at least our

discussion of

networks? 1-38

Introduction

Why layering?

dealing with complex systems:

• explicit structure allows identification, relationship of

complex system’s pieces

– layered reference model for discussion

• modularization eases maintenance, updating of system

– change of implementation of layer’s service transparent to rest of

system

– e.g., change in gate procedure doesn’t affect rest of system

• layering considered harmful?

1-39 Introduction

Internet protocol stack

• application: supporting network applications

– FTP, SMTP, HTTP

• transport: process-process data transfer

– TCP, UDP

• network: routing of datagrams from source to destination

– IP, routing protocols

• link: data transfer between neighboring network elements

– Ethernet, 802.111 (WiFi), PPP

• physical: bits “on the wire”

application

transport

network

link

physical

1-40

11

Introduction

ISO/OSI reference model• presentation: allow applications

to interpret meaning of data,

e.g., encryption, compression,

machine-specific conventions

• session: synchronization,

checkpointing, recovery of data

exchange

• Internet stack “missing” these

layers!

– these services, if needed, must be

implemented in application

– needed?

application

presentation

session

transport

network

link

physical

1-41 Introduction

source

application

transport

network

link

physical

HtHn M

segment Ht

datagram

destination

application

transport

network

link

physical

HtHnHl M

HtHn M

Ht M

M

network

link

physical

link

physical

HtHnHl M

HtHn M

HtHn M

HtHnHl M

router

switch

Encapsulationmessage M

Ht M

Hn

frame

1-42

SENDER:

[Email message] : 1000 bytes

||

\/

[SMTP][Email message] : 1087 bytes

||

\/

[TCP][SMTP][Email message] : 1107 bytes

||

\/

[IP][TCP][SMTP][Email message] : 1132 bytes

||

\/

[ETH][IP][TCP][SMTP][Email message][ETH] : 1159 bytes

||

\/

Packet travels over wire

End-to-End Example: Email

RECEIVER:

Packet arrives over wire (destination in header)

||

\/

[IP][TCP][SMTP][Email message] : 1132 bytes

||

\/

[TCP][SMTP][Email message] : 1107 bytes

||

\/

[SMTP][Email message] : 1087 bytes

||

\/

{[SMTP]}[Email message] : 1000 bytes

||

\/

DONE!

12

Socket programming

goal: learn how to build client/server

applications that communicate using sockets

socket: door between application process and

end-end-transport protocol

Application Layer 2-45

Internet

controlled

by OS

controlled byapp developer

transport

application

physical

link

network

process

transport

application

physical

link

network

processsocket

Operating Systems Support:

Sockets

• A socket is an operating system abstraction

in which a port is embedded

• A port is a communication endpoint

Host, port Host, port

socketsocketProcess Process

• Operations:

– fd = socket(): creates the socket (think OS

metadata to manage communication endpoint)

– bind(fd, port): binds socket to local port

(address)

– Connect(fd, port): establish a connection to a

remote port

– send(), recv(), write(), read(): operations for

sending and receiving data

– close(fd): close the connection

Socket Addresses

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

struct sockaddr{

u_short sa_family; /*address family: AF_xxx value*/

char sa_data[14];/* up to 14 bytes of addr */

}; /* (protocol-specific) */

struct sockaddr_in {

short sin_family; /* AF_INET */

u_short sin_port; /* 16-bit port number */

struct in_addr sin_addr; /* 32-bit netid/hostid */

char sin_zero[8];/* unused */

}; /*sin_port and sin_addr are network byte ordered*/

13

Network Byte Order

• Two ways to map byte addresses onto words:

– Little Endian byte ordering: Intel 80x86, DEC VAX

– Big Endian byte ordering: IBM 360/370, Motorola

68K, MIPS, SPARC, HPPA

• Network byte order (TCP/IP, XNS, SNA

protocols): big-endian in protocol headers

• Byte ordering/alignment routines: htonl, htons,

ntohl, ntohs

Socket System Call

• Creates an endpoint for communication

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

– Family (or domain): AF_UNIX, AF_INET, AF_NS, AF_IMPLINK

– type: SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...

– protocol: typically 0

– Returns a socket descriptor, or sockfd

Services Provided by the

Transport Layer

• Connection-oriented (virtual circuit) versus

connection-less (datagram) protocols

• Sequencing

• Error control

• Flow control

• Byte stream vs. messages

• Full duplex vs. half duplex

• Connection-oriented (virtual circuit)

– Establish a connection

– Transfer data

– Terminate connection

• Connection-less (datagram)

– Each message or datagram transmitted

independently – must contain all information

for delivery

14

Socket programming

Two socket types for two transport services:

– UDP: unreliable datagram

– TCP: reliable, byte stream-oriented

Application Layer 2-54

Application Example:1. client reads a line of characters (data) from its

keyboard and sends data to server2. server receives the data and converts characters

to uppercase3. server sends modified data to client4. client receives modified data and displays line on

its screen

Socket programming with UDP

UDP: no “connection” between client & server

• no handshaking before sending data

• sender explicitly attaches IP destination address and

port # to each packet

• receiver extracts sender IP address and port# from

received packet

UDP: transmitted data may be lost or received

out-of-order

Application viewpoint:• UDP provides unreliable transfer of groups of bytes

(“datagrams”) between client and serverApplication Layer 2-55

Client/server socket interaction: UDP

close

clientSocket

read datagram from

clientSocket

create socket:

clientSocket =socket(AF_INET,SOCK_DGRAM)

Create datagram with server IP and

port=x; send datagram via

clientSocket

create socket, port= x:

serverSocket =socket(AF_INET,SOCK_DGRAM)

read datagram from

serverSocket

write reply to

serverSocket

specifying

client address,

port number

Application 2-56

server (running on serverIP) client

15

Application Layer 2-57

Example app: UDP client

from socket import *

serverName = ‘hostname’

serverPort = 12000

clientSocket = socket(AF_INET,

SOCK_DGRAM)

message = raw_input(’Input lowercase sentence:’)

clientSocket.sendto(message.encode(),

(serverName, serverPort))

modifiedMessage, serverAddress =

clientSocket.recvfrom(2048)

print modifiedMessage.decode()

clientSocket.close()

Python UDPClientinclude Python’s socket library

create UDP socket for

server

get user keyboardinput

Attach server name, port to

message; send into socket

print out received string

and close socket

read reply characters from

socket into string

Application Layer 2-58

Example app: UDP server

from socket import *

serverPort = 12000

serverSocket = socket(AF_INET, SOCK_DGRAM)

serverSocket.bind(('', serverPort))

print (“The server is ready to receive”)

while True:

message, clientAddress = serverSocket.recvfrom(2048)

modifiedMessage = message.decode().upper()

serverSocket.sendto(modifiedMessage.encode(),

clientAddress)

Python UDPServer

create UDP socket

bind socket to local port

number 12000

loop forever

Read from UDP socket into message, getting client’s address (client IP and port)

send upper case string

back to this client

Socket programming with TCP

client must contact server

• server process must first be

running

• server must have created

socket (door) that welcomes

client’s contact

client contacts server by:

• Creating TCP socket,

specifying IP address, port

number of server process

• when client creates socket:

client TCP establishes

connection to server TCP

• when contacted by client,

server TCP creates new

socket for server process to

communicate with that

particular client

– allows server to talk with

multiple clients

– source port numbers used

to distinguish clients

(more in Chap 3)

Application Layer 2-59

TCP provides reliable, in-orderbyte-stream transfer (“pipe”) between client and server

application viewpoint:

Socket System Calls for

Connection-Oriented Protocol: TCP

16

Client/server socket interaction: TCP

Application Layer 2-61

wait for incoming

connection requestconnectionSocket =

serverSocket.accept()

create socket,port=x, for incoming

request:serverSocket = socket()

create socket,connect to hostid, port=x

clientSocket = socket()

server (running on hostid) client

send request using

clientSocketread request from

connectionSocket

write reply to

connectionSocket

TCP connection setup

close

connectionSocket

read reply from

clientSocket

close

clientSocket

Application Layer 2-62

Example app: TCP client

from socket import *

serverName = ’servername’

serverPort = 12000

clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName,serverPort))

sentence = raw_input(‘Input lowercase sentence:’)

clientSocket.send(sentence.encode())

modifiedSentence = clientSocket.recv(1024)

print (‘From Server:’, modifiedSentence.decode())

clientSocket.close()

Python TCPClient

create TCP socket for

server, remote port 12000

No need to attach server

name, port

Application Layer 2-63

Example app: TCP server

from socket import *

serverPort = 12000

serverSocket = socket(AF_INET,SOCK_STREAM)

serverSocket.bind((‘’,serverPort))

serverSocket.listen(1)

print ‘The server is ready to receive’

while True:

connectionSocket, addr = serverSocket.accept()

sentence = connectionSocket.recv(1024).decode()

capitalizedSentence = sentence.upper()

connectionSocket.send(capitalizedSentence.

encode())

connectionSocket.close()

Python TCPServer

create TCP welcoming

socket

server begins listening for

incoming TCP requests

loop forever

server waits on accept()for incoming requests, new socket created on return

read bytes from socket (but

not address as in UDP)

close connection to this

client (but not welcoming

socket)

Disclaimer

• Parts of the lecture slides are adapted from

and copyrighted by James Kurose and Keith

Ross. The slides are intended for the sole

purpose of instruction of computer networks

at the University of Rochester. All

copyrighted materials belong to their

original owner(s).