Upload
diep-nguyen-van
View
216
Download
0
Embed Size (px)
Citation preview
8/6/2019 2 Socket[1]
1/30
8/6/2019 2 Socket[1]
2/30
Batchprocessingsystems
Centralizedsystembasedonmainframe
8/6/2019 2 Socket[1]
3/30
MultiterminalSystems
8/6/2019 2 Socket[1]
4/30
MainEvents
1969:ARPANET
Early
1980s:
TCP/IP 1980:Ethernet
1985:TokenRing,FDDI
1994:Yahoo
1998:Google
8/6/2019 2 Socket[1]
5/30
Sharingresources
Data
Computation
8/6/2019 2 Socket[1]
6/30
Sharingresources
8/6/2019 2 Socket[1]
7/30
Socket
8/6/2019 2 Socket[1]
8/30
Whatisasocket?
Aninterfacebetweenapplicationandnetwork eapp ca oncrea esasoc e
Thesockettypedictatesthestyleof reliablevs.besteffort
connectionorientedvs.connectionless
Onceconfiguredtheapplicationcanpassdatatothesocketfornetworktransmission
receivedatafromthesocket(transmittedthroughthenetworkbysomeotherhost)
8
8/6/2019 2 Socket[1]
9/30
Twoessentialtypesofsockets
SOCK_STREAM
a.k.a.TCP SOCK_DGRAM
a.k.a.UDP re a e e very
inorderguaranteed
connectionoriented
unreliabledelivery
noorderguarantees
nonotionofconnection app bidirectional indicatesdest.foreachpacket
cansendorreceive
3 2 1
App D1
Dest.
socket3 2 1 D2
9
D3
8/6/2019 2 Socket[1]
10/30
SocketCreationinC:socket()
int s = socket(domain, type, protocol); ,
domain:integer,communicationdomain e.g.,PF_INET (IPv4protocol) typicallyused
type:communicationtype SOCK_STREAM:reliable,2way,connectionbasedservice
SOCK_DGRAM:unreliable,connectionless,
othervalues:needrootpermission,rarelyused,orobsolete
protocol:specifiesprotocol(seefile/etc/protocols fora
NOTE:socket calldoesnotspecifywheredatawillbecomingfrom,norwhereitwillbegoingto itjustcreatestheinterface!
10
8/6/2019 2 Socket[1]
11/30
Ports
Eachhosthas65,536orts
Port1 Someportsarereserved ors eci ic
Port65535apps
20,21:FTP23:Telnet
80:HTTP
Asocketprovidesaninterfacetosenddatato/fromthenetworkthroughaport
2000portsarereserved)
11
8/6/2019 2 Socket[1]
12/30
Addresses,PortsandSockets
Likeapartmentsandmailboxes
Yourapartmentbuildingaddressistheaddress
Thepostofficeisthenetwork
Thesocketisthekeythatgivesyouaccesstotherightmailbox(onedifference:assumeoutgoingmailisplacedbyyouinyourmailbox)
Q:Howdoyouchoosewhichportasocketconnectsto?
12
8/6/2019 2 Socket[1]
13/30
Thebind() function
associatesand(canexclusively)reservesaportfor
int status = bind(sockid, &addrport, size);
,
sockid:integer,socketdescriptor
addr ort: struct sockaddr the IP address and ort ofthemachine(addressusuallysettoINADDR_ANYchoosesalocaladdress)
s ze:t es ze n ytes o t ea rpor structure
13
8/6/2019 2 Socket[1]
14/30
ConnectionSetup(SOCK_STREAM)
Recall:noconnectionsetupforSOCK_DGRAM
connec onoccurs e ween wo n so participants
connection
active:initiatesconnectionrequesttopassiveside
Onceconnectionisestablished,passiveandactive
participantsaresimilar
bothcansend&receivedata
eithercanterminatetheconnection
14
8/6/2019 2 Socket[1]
15/30
Connectionsetupcontd
Passiveparticipant Active artici ant step1:listen (forincoming
requests)
step3:accept (arequest) step2:request&establish
step4:datatransfer
Theacceptedconnectionisonanewsocket
step4:datatransfer
Theoldsocketcontinuestolistenforotheractive
PassiveParticipant
lsockasock1 asock2
Why?
15
Active1soc e
Active2soc e
8/6/2019 2 Socket[1]
16/30
Connectionsetup: listen &accept
Calledbypassiveparticipant
int status = listen(sock, queuelen); status:0iflistening, 1iferror
sock:integer,socketdescriptor queuelen:integer,#ofactiveparticipantsthatcanwaitfora
listen isnonblocking:returnsimmediately
int s = accept(sock, &name, &namelen); s:inte er thenewsocket usedfordatatransfer sock:integer,theorig.socket(beinglistenedon) name:struct sockaddr,addressoftheactiveparticipant namelen:sizeof(name): value/resultparameter
must
e
set
appropriate y
e ore
ca adjustedbyOSuponreturn
accept isblocking:waitsforconnectionbeforereturning
8/6/2019 2 Socket[1]
17/30
connect call
int status = connect(sock, &name,name en ;
status:0ifsuccessfulconnect, 1otherwise
sock:integer,sockettobeusedinconnection
name:struct sockaddr:addressofpassiveparticipant
namelen:integer,sizeof(name)
connect isblocking
17
8/6/2019 2 Socket[1]
18/30
Sending/ReceivingData
Witha connection(SOCK_STREAM): , , ,
count:#bytestransmitted(1iferror) buf:char[], buffertobetransmitted len:integer,lengthofbuffer(inbytes)totransmit flags:integer,specialoptions,usuallyjust0
= count:#bytesreceived(1iferror) buf:void[], storesreceivedbytes
:
y es
rece ve flags:integer,specialoptions,usuallyjust0
Callsareblockin [returnsonl afterdataissent
18
(tosocketbuf)/received]
8/6/2019 2 Socket[1]
19/30
Sending/ReceivingData(contd)
Withouta connection(SOCK_DGRAM):
int count = sendto(sock, &buf, len, flags, &addr,addrlen);
count, soc , u , en, ags:sameassen
addr:struct sockaddr,addressofthedestination
int count = recvfrom(sock, &buf, len, flags,,
count, sock, buf, len, flags: sameasrecv
name:struct sockaddr,addressofthesource
19
namelen:sizeof(name): value/resultparameter
8/6/2019 2 Socket[1]
20/30
close
Whenfinishedusingasocket,thesocket
s ou ec ose :
status = close(s);
status:0ifsuccessful, 1iferror
s:thefiledescriptor(socketbeingclosed) Closingasocket
closes a connection for K TREAM _
freesuptheportusedbythesocket
20
8/6/2019 2 Socket[1]
21/30
Socketcommunication
8/6/2019 2 Socket[1]
22/30
Thestruct sockaddr
Thegeneric: TheInternets ecific:
u_short sa_family;char sa_data[14];
struct sockaddr_in {short sin_family;u_short sin_port;
sa_family
struct in_addr sin_addr;char sin_zero[8];
}; specifieswhichaddress
familyisbeingused
determineshowthe
sin_family = AF_INET
sin_port:port#(065535)
sin addr:IPaddress
remaining14bytesareused
_
sin_zero:unused
22
8/6/2019 2 Socket[1]
23/30
Addressandportbyteordering
Addressandportarestoredasintegers
_ _
in_addrsin_addr;(32bit)
_u_long s_addr;
};
Problem:
differentmachines/OSsusedifferentwordorderings
littleendian:lowerbytesfirst
bigendian:higherbytesfirst
thesemachinesmaycommunicatewithoneanotheroverthenetwork
12.40.119.128
BigEndianmachine LittleEndian
machine
23
. . .
128 119 40 12 128 119 40 12
8/6/2019 2 Socket[1]
24/30
Solution:NetworkByteOrdering
Defs: os y e r er ng: e y eor er nguse y
ahost(bigorlittle)
bythenetwork alwaysbigendian
AnywordssentthroughthenetworkshouldbeconvertedtoNetworkByteOrderpriortotransmission(andbacktoHostByteOrderoncereceived)
24
8/6/2019 2 Socket[1]
25/30
UNIXsbyteorderingfuncs
u lon htonl u lon x u lon ntohl u lon x_ _
u_short htons(u_short x);
_ _
u_short ntohs(u_short x);
Onbigendianmachines,theseroutinesdonothing
Onlittleendianmachines,theyreversethebyteorder
128.119.40.12128.119.40.12
BigEndian
machine LittleEndian
machine128 119 40 121281194012
128 119 40 12 128 119 40 12
n
tohl
25
8/6/2019 2 Socket[1]
26/30
Dealingwithblockingcalls
Manyofthefunctionswesawblockuntilacertainevent
connect:
until
the
connection
is
established recv, recvfrom:untilapacket(ofdata)isreceived
sen , sen o :unt ata spus e ntosoc et s u er
Forsimpleprograms,blockingisconvenient
multipleconnections
simultaneoussendsandreceives
s mu taneous y
o ng
non
networ ng
process ng
26
8/6/2019 2 Socket[1]
27/30
Dealingw/blocking(contd)
Options:
turn
off
the
blocking
feature
(e.g.,
using
the
fcntl file
descriptor
controlfunction)
.
Whatdoesselect do?
canbepermanentblocking,timelimitedblockingornonblocking input:asetoffiledescriptors
output:infoonthefiledescriptorsstatus
socketwillreturnimmediately
27
8/6/2019 2 Socket[1]
28/30
select functioncall
int status = select(nfds, &readfds, &writefds,excep s, meou ;
status:#ofreadyobjects, 1iferror
readfds:listofdescriptorstocheckifreadready
exceptfds:listofdescriptorstocheckifanexceptionisregistered
timeout:timeafterwhichselectreturns,evenifnothingready canbe0or(pointtimeout parametertoNULL for)
28
8/6/2019 2 Socket[1]
29/30
Tobeusedwithselect:
Recallselect usesastructure,struct fd_set
ifbitiissetin[readfds, writefds, exceptfds],selectwillcheckiffiledescriptor(i.e.socket)iisrea y or rea ng,wr t ng,except on
Beforecallingselect: _ : FD_SET(i, &fdvar):tocheckfiledesc.i
int FD_ISSET(i, &fdvar):booleanreturnsTRUE
iffiisready
29
8/6/2019 2 Socket[1]
30/30
Otherusefulfunctions
bzero(char* c, int n): 0snbytesstartingatc
ethostname char *name int len : ets the name of thecurrenthost
gethostbyaddr(char *addr, int len, int type): convertsIP
inet_addr(const char *cp): convertsdotteddecimalchar
stringtolonginteger inet_ntoa(const struct in_addr in): convertslongtodotted
decimalnotation
Warning:checkfunctionassumptionsaboutbyteordering(hostornetwork). Often,theyassumeparameters/return
30