what is the internet?web.eecs.umich.edu/~sugih/courses/eecs489/lectures/02... · 2016-01-10 ·...
TRANSCRIPT
Lecture2:NetworkProtocols
andSocketsProgramming(TCPClient)
Computer Networks
WhatistheInternet?
Lastlecturewesaid...ontheInternet• dataisparceledintopackets• eachpacketcarriesadestinationaddress• eachpacketisroutedindependently• packetscanarriveoutoforder• packetsmaynotarriveatall
Ontopofthispacket-switchednetwork,theInternet
providestwotypesofdeliveryservice:• connectionless(datagram,UDP,e.g.,streamingmedia,games)
• connectionoriented(bytestream,TCP,e.g.,web,email)
WhatistheInternet?
Connectionorientedserviceprovides:• end-to-endreliability(senderretransmitslostpackets)
• in-sequencedelivery(receiverbuffersincomingpackets
untilitcandelivertheminorder)
Somefundamentalquestionsabout
packet-switchednetwork:• howdoesarouterknowwhichroutertoforwardapacketto?
• howdoesareceiverknowthecorrectorderingofpackets?
• howdoesasenderknowwhichpacketislostandmustbe
retransmitted?
Theanswertoalloftheserelyonnetworkprotocols
NetworkProtocols
Networkprotocols–rules(“syntax”and“grammar”)
governingcommunicationbetweennodes(sender,
router,orreceiver)
• exampleprotocols?
Protocolsdefinetheformat,orderof
messagessentandreceivedamongnetwork
entities,andactionstakentotransmit
message,andonmessagereceived
InternetProtocolStack
applicationprotocol:supportnetwork
applications• HTTP,SMTP,FTP,etc.
transportprotocol:endhost-to-endhost
datatransfer• TCP,UDP
networkprotocol:routingof
datagramsfromsourcetodestination• IP,routingprotocols
linklayerprotocol:datatransfer
betweenneighboringnetworkelements• Ethernet,WiFi
physicalprotocol:gettingbits“onthewire”
application
transport
network
link
physical
LayeringintheIPProtocols
InternetProtocol
TransmissionControl
Protocol(TCP)
UserDatagram
Protocol(UDP)
SMTPHTTP
Cellular
Data
WiFiEthernet
NTPDNSFTP
source
application transport network
link physical
destination
application transport network
link physical
network link
physical
link physical
router
switch
NotallNetwork
Elements“Speak”
AllLayers
WhyLayering?
Networksarecomplex!Many“pieces”:• applications• hosts• routers• linksofvariousmedia
Onewaytodealwithcomplexsystems:• explicitstructureseparatesoutthepieces• modularizationmakessystemeasiertomaintainand
update• changingtheimplementationofalayeristransparenttotherest
• changeofimplementation≠changeofservicedefinition!
CreatingaNetworkApplication
Examplebenefitsoflayering:
• programmerscanwriteappsthat• runondifferentendsystemsand
• communicateoveranetwork
• e.g.,browsercommunicates
withwebserver
• nosoftwarewrittenfor
devicesinnetworkcore• networkcoredevicesdono
functionatapplayer
Thisdesignallowsforrapid
appdevelopment
application transport network data link physical
application transport network data link physical
application transport network data link physical
Server:• aprocessthatmanages
accesstoaresource• processormachine?
• usuallyhasawell-known,
permanentIPaddress
• waitsforconnection
• canuseserverfarm/clusteror
cloudcomputingforscaling• howdoserverfarmsmaintain
asingleIPaddressexternally?
Client-ServerComputing
Email(SMTP)usesthe
client-serverparadigm
Client:• aprocessthatneedsaccesstoaresource
• initiatesconnectionwithserver
• maybeintermittentlyconnected
• mayhavedynamicIPaddresses
• clientsdonotcommunicate
directlywitheachother
Alternative(s)toclient-server?
Client-ServerComputing
Email(SMTP)usesthe
client-serverparadigm
socketsocket
Sockets
Processsends/receives
messagesto/fromits
socket
Socketanalogoustodoor• sendingprocessshovesmessagesoutthedoor
• sendingprocessreliesontransportinfrastructureon
theothersideofthedoorto
delivermessagetothesocket
atthereceiverprocess
process
TCPwith
buffers,
variables
hostor
server
process
TCPwith
buffers,
variables
hostor
server
Internet
controlled
byOS
controlledby
appdeveloper
SocketsAPI
physical
data-link
network
transport
applicationsocketAPI
AnApplicationProgrammerInterface(API)to
accessthenetwork
• setoffunctionprototypes,datastructures,andconstants
• allowsprogrammertolearn
once,writeanywhere
• greatlysimplifiesthejobof
applicationprogrammers
AddressingSocket
Aserverhostmaysupportmanysimultaneous
applicationprocesses,eachwithoneormoresockets
• webservers,forexample,usesadifferentsocketforeach
connectingclient
Whenapacketarrives,howdoesthekernelknow
whichsockettoforwarditto?
• bythehost’sunique32-bitIPaddress?• istheIPaddresssufficienttoidentifyasocket?
HowDemultiplexingWorks
HostreceivesIPpackets• eachpackethassourceanddestinationIPaddresses
• eachpacketcarries1transport-layersegment
• eachsegmenthassourceand
destinationportnumbers
HostusesIPaddresses&port
numberstodirectsegmentto
theappropriatesocket
sourceport# destport#
32bits
application
data
(message)
otherheaderfields
TCP/UDPsegmentformat
Multiplexing/Demultiplexing
client
IP:B
P1
client
IP:A
P1P2P4
server
IP:C
SP:9157DP:80
P5 P6 P3
S-IP:A
D-IP:C
SP:9157DP:80
D-IP:C
S-IP:B
SP:5775DP:80
D-IP:C
S-IP:B
=process=socket
deliveringreceivedsegments
tocorrectsocket
Demultiplexingatrcvhost: transmittingdatafromvarious
sockets,envelopingdatawith
headers(laterusedfor
demultiplexing)
Multiplexingatsendhost:
Connection-orientedDemux
SocketidentifierincludesboththeIPaddressesand
portnumbersassociatedwiththesocketonthehost
Exampleportnumbers:• HTTPserver:80• Mailserver:25• See/etc/services
Receiverkernelusesallfourvaluestodirectpacketto
appropriatesocket
Somewhereinthesocketstructure:
TCPServer: TCPClient:
SocketAddresses
matchedagainstincoming
packetdestination
copiedtooutgoing
packetdestination
Sockets
Whatexactlyaresockets?• anendpointofaconnection• identifiedbytheIPaddressandportnumberofbothsenderandreceiver
• APIsimilartoUNIXfileI/OAPI(providesafiledescriptor)
BerkeleysocketsisthemostpopularnetworkAPI• runsonLinux,MacOSX,Windows
• canbuildhigher-levelinterfacesontopofsockets• e.g.,RemoteProcedureCall(RPC)
BasedonC,singlethreadedmodel• doesnotrequiremultiplethreads
ProcessFileTableand
SocketDescriptor
StevensTCP/IPIllustratedv.2p.446
sd
protocol switch table
TypesofSockets
Differenttypesofsocketsimplement
differentservicemodels• datastreamvs.datagram
Datastreamsocket(e.g.,TCP)• connection-oriented• reliable,inorderdelivery• at-most-oncedelivery,noduplicates
• usedbye.g.,smtp,http,ssh
Datagramsocket(e.g.,UDP)• connectionless(justdata-transfer)• “best-effort”delivery,possiblylowervarianceindelay
• usedbye.g.,IPtelephony,streamingaudio,
streamingvideo,multi-playergaming,etc.
DataStreamvs.Datagram
Stevens
Datastreamtreatsdataasonecontinuousstream,not
choppedupintoseparate“chunks”
SimplifiedE-mailDelivery
Atyourend,yourmailer(client)• translatescs.usc.edutoitsIPaddress(128.125.1.45)• decidestouseTCPasthetransportprotocol(Why?)
• createsasocket• connectsto128.125.1.45atthewell-knownSMTPport#(25)• parcelsoutyouremailintopackets
• sendsthepacketsout
SimplifiedE-mailDelivery
OntheInternet,yourpacketsgot:• transmitted
• routed• buffered• forwarded,or
• dropped
Atthereceiver,smtpd(server)• mustmakea“receiver”aheadoftime:
• createsasocket• decidesonTCP• bindsthesockettosmtp’swell-knownport#
• listensonthesocket• acceptsyoursmtpconnectionrequests• recvesyouremailpackets
Stream/TCPSockets
time
initialize
establish
dataxfer
terminate
socket ()
connect ()
send ()
recv ()
close ()
Client
socket ()
bind ()
listen () accept ()
recv ()
close ()
send ()
Server
WhenaTCPserveracceptsaclient,itreturnsanewsockettocommunicatewiththeclient
• allowsservertotalktomultipleclients
• sourceaddress&portnumberusedtodistinguishclients
Initialize(TCPClient)int sd; if ((sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
perror("socket"); printf("Failed to create socket\n"); abort(); }
socket()createsasocketdatastructureandattachesittotheprocess’sfiledescriptortable
Handlingerrorsthatoccurrarelyusuallyconsumes
mostofsystemscode
Establish(TCPClient)
unsigned short server_port; char *servername; // both assume initialized struct sockaddr_in sin; struct hostent *host = gethostbyname(servername); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = *(unsigned long *) host->h_addr_list[0]; sin.sin_port = htons(server_port); if (connect(sd, (struct sockaddr *) &sin, sizeof (sin)) < 0) { perror("connect"); printf("Cannot connect to server\n"); abort(); } connect() initiatesconnection(forTCP)
SendingDataStream(TCPClient)
int send_packets(char *buffer, int buffer_len) { sent_bytes = send(sd, buffer, buffer_len, 0);
if (send_bytes < 0) perror(“send”);
return 0;
}
• returnshowmanybytesareactuallysent
• mustlooptomakesurethatallissent(unlessblockingI/O)
Whatisblockingandnon-blockingI/O?
Whydoyouwanttousenon-blockingI/O?