network protocol and sockets programming (tcp client)

7
Lecture 2: Network Protocols and Sockets Programming (TCP Client) Computer Networks What is the Internet? Last lecture we said . . . on the Internet data is parceled into packets each packet carries a destination address each packet is routed independently packets can arrive out of order packets may not arrive at all On top of this packet-switched network, the Internet provides two types of delivery service: connectionless (datagram, UDP, e.g., streaming media, games) connection oriented (byte stream, TCP, e.g., web, email) What is the Internet? Connection oriented service provides: end-to-end reliability (sender retransmits lost packets) in-sequence delivery (receiver buffers incoming packets until it can deliver them in order) Some fundamental questions about packet-switched network: how does a router know which router to forward a packet to? how does a receiver know the correct ordering of packets? how does a sender know which packet is lost and must be retransmitted? The answer to all of these rely on network protocols Network Protocols Network protocols – rules (“syntax” and “grammar”) governing communication between nodes (sender, router, or receiver) example protocols? Protocols define the format, order of messages sent and received among network entities, and actions taken to transmit message, and on message received

Upload: hoangminh

Post on 12-Jan-2017

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Network protocol and sockets programming (TCP client)

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

Page 2: Network protocol and sockets programming (TCP client)

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!

Page 3: Network protocol and sockets programming (TCP client)

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

Page 4: Network protocol and sockets programming (TCP client)

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:

Page 5: Network protocol and sockets programming (TCP client)

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

Page 6: Network protocol and sockets programming (TCP client)

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

[email protected]

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

Page 7: Network protocol and sockets programming (TCP client)

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?