You are on page 1of 44




Introdldion to Socket Prcgrammhg -
overuiew of TCP/IP Protocots
introduction to Sockets - Socket address Strlctur€s Blte odertng
flnctions - address conversion tunctions - Elemenrary TcP sockets -
socket, connect, bind, listen, acceptr read, wrtte, close tundrons - rteratrve
Seruer - Co.crrrenr seNar,
1. Gro!, th6 ost laYers by lunGU.n,
The seven laye6 of the OSI modelbelongrng to thee subgroups. Physical,
data llnk and network the n€twork support layeB; they deal wrth the
physicl aspe.ts of
movlng data fbm one device to another. Sesslon,
Presentation and appll.ation layeE aE the user support layeE; they altow
htebpeEblllty amonS unelated software systems, The transport layer ensuEs
end to-end Ellable data trans
The transpolllay.r .rca 6mmlnl..tlon beiween the souEe ard
destln.tlon. What are th6 three event.lnvolved in:.onn..tion?
Creatlng a @nnedlon involves three sieps: .onnection €tablishme.t,
data transier and connection retease,
3, D.fin€ flow.o.trol,
Flow @nircl retuts to a set of procedures used to restnct the amount of
data, The sendercan send before sa ting fo. acknowledgment.
4. Mention the categorles offlow.ontrol,
There are 2 methods have b€en developed to contrclflow ofdata
a.ross.ommunication links,
> Stopa.d wait- seid one from at a the.
t Sliding window- end everat franes ar a time,

Prcpared By: Mrc. S, Artheeswart APlrT, MEC
i4r, P. Saravanan Ap/rr, MEC

rr B51l NEn ORt< PROGM

5. Wh:t I. the function or .top and wait flow 6ntrot?
ln this method, rhe sender sends ode fEme and waiis for an
a-lnosled!emenr b.f o'e se4d,ng.
6. M.ntion rhe adva ag. dnd disadvahtage ot stop and wait ftow contrct,
Advantage: simp|ciry
D,advanrage: rnem.ienry.
7. what ts pigqy t acking?
Piggybacklng means combining data ro send and acknowtedqement
of the frame re.eived in one st.gte frame. ptggy backing @n save
bandwidth becalse the overhead from a data frame end EnACK
be combhed intojlsi one frame
a, what are thc n6two* support tayeF and th€ usef .lpport tEyeB?
Network support tay€B:
The nehvork support tayeB are physicat byer, Data tink tayer and
Network layer. These deats wtth specit5cdtions, physicat
(oTecflon, transooa umtn9 d4d ?.,abrtrty,
U.€r suppon HyeEr
The user support taye6 are: S€ss,on tayer, presentation tayer,
Appli.atlon larer, These a ow interoperabilty among unetnted software

9. What arc th. reEponstbiti 6ot n6rwort t.yer?
The nerwork taver is r6po^sib'e ror the sou@ro-dejtin.Uon
delivery ol packet ac,c mutupte nerwork [nks. The specific
responsrbilites of network tayer tnctude rh€ fo,towtngl
t rogtct€ddE$tng,
. Rou ng.
1o.wh.t ac data
ln datagram apprcach, each packet ts treated indep€nden y fbm
a Ever wrei ole parker represenrsjlst a Dtace ora .utti-oacker

t6nsmi$ion, $e network treats itatthough it exisred atone. packets jn
thistechnoloqy ar€ refered ro.s datagrEm.
ll.D.tine IP.ddre5s.
lP address is the 32,bir number for represenrinq a host or system
in the net{o.k. one po*ion of the Ip address l.dt.ates a networking and
the other represenrs the host in a nerwork.
12,Wi.t is fundlon oftransport tayer?
The protocotin the transpod tayer in rhe detivery of dara
from one apptiGtion proqr€m on one devi@ to an app[caton posrad

Prcparcd By: ME, S, Artheeswart aplrr, r4Ec
lilr. P, Saravanan Ap/n. I4EC

/' -

d .mther d4ice. lney ad as a tink between the upper tayer potoots
and th€ seruies prcvidei by the tower layer,
t'Ulr.t .E thc dlti€s of tne tranEport taycr?
The serutces provid€d bythe hanspo.t tayer
. End-to end deiivery
r Addressinq
. Retiabte detivery
. Flow Lonrol
. Mutrptexins
l4,What 13 tfte differenc. betw.€r .etEo.k l.y€r d.tiv.ry .hd tne
traEpon hy.r d.llvery?
etwork layer d.livery Transport l.yer dellverv
he rtwor^ laye, E I rhe rrdnspod tayer s rerpo;sib€
i.<ponsible lor rre sou.ce ro I ror *ure 'o oestrnauon oerivery
dqunatron delivery ol packer I of rhe enr're mesage.
acros muluple networl li.k,
the ,our Gpect rct.ted to tie d.fiv.ry of dat.i
. Tne lou, aspe.ts are,
o Emr@ntDt
o Sequeh@ control

. Dupttoflon.onrmt
l6.What ls me.nt by
At the *ndhg and recetvlng end of the rransmtsston/ lcp dtvtds
long transmt$tons intosmatterdatE u;its and packages each into6 frame
clled a sesme.t.
lT,What is meantby s.gment flon?
When the srze ofthe data lntt re@ived from the upper tayer is too
long forthe netwo.k tayerdatagram ordata thk tayerf€me to handte,
thetEnsport protocotdivides tr tnto smalerusabte btocks. The dividirg
pbce$ ts cfled segmentation,
la,wh.t a. heant by con.atE.adon?
The size of the data unit belongtng to stnqte *sstons are so smalr
that sev€ flt togerh€r tnto a singte daragram or t6me, the t.ansport
proto@l combines them tnto a stngle data untt, The pMes is
called concatehation.
lg.What ar€ th. rypei of hlttiptextng?
The types of multiplexing arer ay: Mrs. s. Artheeswari AP/IT,lrlEc
I4i P. saGvanan AP/IT, MEC


t upward muttiptex,ng
. Oownward nutiplexlng
2o.What are the two possible tr.n.porr
Two basE ryp.sofnanspod seruices are,
o Coniection serui.e
o connectionle$ seNies
,l.lhe tran.port lay€r .EatB tfie conn..don b.tween .our.e .nd
destination. Wh.t .rc tft. thlB .v.nts lnvoked in tne @nnetior?
For senty, the thcDort lays may @.te a @nnectbn betwen
tfie two enil ports.
A @nnection is a slnqle logl6l path b.twen the eu@ and
destination that Is eseiated with all packets in . mesge. creting a
connectlon involve the <teps:
.connedlon establishment
.Data tcnsfer &Connectlon release.
22. Wh.t l. h6nt hy @rgestlon?
conqestio.ln a networkoccuB ifu*.sendsd.ta intd rhe
network ata rate greter than thatallowea by network rasou@'
23. Wh.t l. the purDos6 of Dom.ln ame Sy.tem?
Domaln Name System en h.p a host name to €n IP .ddre$ and
lonveEely an IP addE$ro host name.
,4. Dl*u.. th. thr.. m.ln dMrion of th€ dom.ln..m..Da6.
Ddaln name space ls dlvlded into thre dl ferent ectrons:
senencdom9lE, country dom.hs & lnveEe domaln,
. G.n.ri. domrln: Define reglstered hosts adodlng to thelr gen€ric
behavior, uses gene c sumxs.
! Courtry domalnr Uss two characteE to identify a @untry as the last
.Irv.E. domaln: Fhds thedomain naheqiven the IP addre$,
25. What ll th€ p.Irclpl. dltteEnc6 b6twen .onn.ctionl.s
@mdunL.tlon and onnection orl.rted.ommurl.ation?
Network ls a (onnection onent€d. Here user uses the @nnst;n
and then relea* the .onnectlon. Typl@lly one slde mak6 a prop€al
otherside @n aceDt lt. LcrleleDhone systems.
In cohnecnonls each mGsage crls the tull destinauon addB
and each one ls Euted thbugh the system independ€nt of all oties, The
fi6tonesend wlll bethe flEtone toairive. Eg:Postal system.
26. State f€w adv:.tage. of IPvs over IPv4.

s. Artheeswarr AP/IT, MEC
P.saEvanan aPlrr, tlEc

wh.rc . Support for r6our.ph6m. S.d.. Tils is @lled EphemeEl port number.t i. Artheesrart AplIT. tocat host ! Loet client proSEm . PushinS DEra . .ket . choen Endomly by the TcP eftwa€ running on the toct hosr. Fouractionsare needed tc close the. 30. iYEC . oth.? r{I UNII 1 r t ilrsadd'B spae . r Hosr s sends a segmenr acJ<nowtedging the reqlest ofA. IT 2351 / ENVORX PRO@AIIIIIiIG AND I.onnection establlshhent.t ls So. .onnection rs closed ii one dire.ddress? The cohbination ofan Ip addrcss and a porr number ts clted socket Addres.ulationandDe. Explain about connedton terhinarion. l. definirions and pbcedures tor wntrng clientseNer prog6hs. . P. What . Xd optioc . so. t4EC I4r. . ursent Data 29.ral Portnqmb€r? A cltent pEqram running on th€ to@t @mputer deftnG ttsetf wtd1 a port number.lement needed for conmonicauons? . After this the .rion bLt not n ih.6 th.tienFs€ruer Prcpared By I l4rs.Uo.capsutation r Budedag . Remote seder prosram. Support for more securily. Wh. 31. 33. TcP op.r. . wh.upDorts to writ.a l. Beilr h. 32. i Host A acknowtedses the requesr of B. when Host B has finished sendins its own data. Wh.e allocation. Give son€ common APL that .. it sends a segment to indtere thar twantsto ctose the connecuon.4ultiplexrngandDe-multtpJexlng . SaEvanEn AP/r.onnections tn both d rections: . f6mar .r dlrecton.k€t lnterface? socket intefsc rs a set ofdectararions.g its wlsh for . 27.t . Host A sends a segment anrou. 24. A!l@n@ for dtension.

tu.d by s.t uctlrc? An IPV4 addBs is dehned as a sttu. L- 37.littlecndli.h ek tdtMpEs ro@mmunrGte using Uop. MEC .trn.ture holdsan rP addrB as a 32 bitbinary number. stru.IT 2351 / NETWORK PROGMMMING AND I. SaEvanan APIIT. Whrt i.ddt 35..e t Transporr ayer Inter'ae :1 stream Interfac€ + Thread rnreridce + Remote PEedureGtt 34. > StEam $..k€t interfae? Th€ scket inte.IANA6E}4ENI I' lse the 35.UDp uses a pair of dltag6m skets to send a mesge frcm appll@tion prcgEm to another a.ddr t in_.k t atto$ p'oe<a to ommuni@re using fCPlP.fae dG6G the typer of s@ket!. MEC I.rCP !s a patr of skts to @nne€t one app[@tion prc96m to nnotier acc ihe Intemet. Artheeswan AplrT.t t. The$ the rnremet. > It w.€ndLan system stocs the most signifi€ant byte of data in the starflng addre$ of the data unit.e G ed i. byt.r = programs? Sone common APIS that slpports ro wrire ctient-seryer proqGms arc .4i P. Socker tnierf. the datagEm sodet aid dE 6w edet. Prcparcd By: 116.Gk tr p@vtde a. What ar€ the th@ $cket tl'D€ d. order? A cohputer system that us$ lttue endlan ststeo stores the lest signifcnt byte of data in the starttnq address ofrhedata !nir. They arc steam ecket._. What i3 Biq-Ehdl.ddr_t s_.r byte order? A @hputer system that uses btg. > Daa. which ontains onty one fietd cled s addr if rype in addr r.l$ . addr.ify the Internet to IcMp or ospF rhar dlre. Spe.

This function retums an integeri 0lorsuess and -1 ifany etro.€ The most common byte han putation fundtons are memset. I.t sock:ddrcs. whatarethe Byte iranipularion f(n.cesful.m.hs€t (vold *d.. lnt blnd(int so. $ckfd is the socket descripror.tions: vold *m.rddr con.ln th. tocataddr is the pointer to the socket address of the local machine and localaddnen is th..onsr vold int mem. Arrheeswart AP/IT.ize_t len).taddrr sockten-t loc. memcpyl memcmp. 'desi. t4EC It lakesthEe int€ger arguments and retum an integerres! !.st. Oeclaratlon for byte manipulatton fui. whtch untquely defines the @ated socket if the cratlon rs su.. Int e.onrt votd *secon.tiohs? 8ow they a. int.nll. void *m. Expl. S.k€t (const void *firs& .ln the bhd fun. the c enr f6t needs to catt the sockettundion ln order to use the retur.ed value as the socket descriptof.nd UDP- Thls tundlon etums a socket decdptor. PEp. 39. To u* thls fundion. Thls lunctlon sets values for Uie local socket address.tlon? Tte bind functlon blndsa socket lo a ocal socketaddr€ss by addrnc the lo@l socket address to an aleady created socket. It retums -1 iI ther€ is an emr. int (vold +sr.IT 2351 / IIETW(XX PROGRAMMTNG AND MAI{AGEMENT 34.k€t(lnt l. P. saEvanan AP/IT. Expl.hrr size_r ten). By I titts.4Ec . int typ.ot)i -dennes lhe prctocol grcup -defnes the type of socket -set to zeb forTcP.tlon? The socket tunction is u*d by a pro@$ to create a socket.ddrlen). *toc. stze_t ten). length of the lool socket address. The socket descrlptor ls used by other tunctions to refer to the 40.

nLddr.. To use this tun.kr4 6nrt vold *id.e. SaEvanan AP/IT.o. 0 for suc@s and -1 rf ani eer. tne dienifiEt needs to cail the ecket fundion ln order to use the rctumed EIE 6 th€ sod(et de*npior. lt cEat6 a passive scket from an un@nnecled $<l€L BelbrE @lling t'te listen tunctron. P. .ll? A @n. fte return value 's the new eLket des.llert:ddrl6n)l Thls function create 6 new socket (child ectet)that @n be u*d by a child *ruerto connecttothe cllent.tion to a remote pro.t so.k.ctive @rn.tion.ndto(int . lhis!dog is tn€ .IT 2351/ NETWORK PROGRAMMING AIIO MANAGEMEiIT 41. This tunctron lnforms the opehtlrg system tnat tne ffi is @dy to acept @nnedion thEugh lnrllrt. Expl.kl. socldd ls the soctet degidor .Ee_t bufl. 41. MEC .t s.o. 42. .and *tueGddrren is the length ofthe 106ls. slte.k.ket address.l. @nrt struct sockaddi6..'.r).pt luncdon? The acept tundron rs @lled by a TcP *d. all the information needed fora new $cket is omvided by tr ope-ctng syctem. Expl. so. *toaddr.odrld.ln . s6.ess i6 e3tablBl ed? The.t.. sockletr_troaddrt.*tlonless prc.endto systGm c.ll.n_t . ll. MEC Page I Mr. . Artheesari ApllT. .nter to rhe butrer holdhg tie me$age to be 5ent. Inas tundion rctums an ihteqer.ddress *serveraddr. 0 for suee$ and :1 lf any eror. Ifthee arc no Equ6ts dP a(ept tunctJon E put to sleep. . sockfd rs uE ed(et dEnptor .n tunctid? only the TcP e er 6lls tfie lirnen tuncuon.ln d!.onnect(ant . buf rs the po. the socket mlst akeady be @atEd and rrE liEl addls 6elds set.ess (pro@$ usinq UOP) i*us thesendto system cll to send data to a po@$. lnt flags.onst stru.lmber of Equets that en be queled for this 6nne.€s .tru.d d rcE :cli.d the llags flelds PEpaEd By : M6.*ryeraddr is the pornter to the remot€ soc*€t add.n ts€ruerad.t .nont sockLr ht b.r t moE the fiEt Connectlon requet frofr thE cocpondlng quse. E.rlptor. rt4.lrletr).his tunctim rcurms an hteger. Expl.kd is the socket dGcnptor. . buflen defin6 the lengrh of rhe buffer. How an .onnect tundion is u*d bya process (usually a cl:enD io esiablish an active @nnedlon to a emote piocss (normally a server) lrt .@pt(lnt sockld.ction sets values for the remote setet add6. Or.

terhirar€d? t3 The do$ tunction ls used by a proe$ to close a $cket and termlnate a TCPconne.d 6ysrch @tt? A connecnon{riented prcc6 (oD@s using TCP) isues rhe Ead system cll to @lve datagdms from a Enore po.ection oriented process (prccess ushg-rcP) tsslesrhewrlte system callto send daraqramsto a Emote prc. I4EC .kfd is the socket descriptor/ buf ts the potnrer to the bufrer where the dafd to be *nt is storedr buflen defln€ the tengrh of the bufier. Thls tunction Etums the ouhber of chaEcteu send tfrhere ts no emr and 0 oth€Bt*. struct.Ft. Exphln rc.cvfrcm .-rhis tunctio. This tunctton returns the number or bytes *nt(wrttten) tf su@s.rrcmaddr.ddre6s. .onst votd :but. .ess. s.ock. TCPconn€dio._t write(tnt .t votd *b!t. sria_t rc. sir6_t bufl. sockfd ls the socket descitptor.. 47.ha6.. so.tets se. and tn€ flaqs fields specifies out of band data or lodkahead m6*ges. MEc !4r P.d toaddrten isthe length of tle seket addre$. buflen defines rhe tength of rhe butrer.tze_t bfftenr int flag3.n). Nomaly it is ser to zeb. Artheeswari AP/IT. Fromaddr ls rhe pointer to the socket addre$ of tne *nder.o. a.m ca[? A con. Erplain r.o.if6 out-of-band data or took ahead mssages.ysteh._t *r. SaravEnan Ap/tT..IT 2351 / IETIyORX PROGRAIIIIIIIIG AND MNAGEMENT 5De. 46. Toaddr isthe pointerto the socker address ofrhe receiver. buf ls the potnter to the butrer wher€ the mesge wJtt be stored. and fromaddrten is ihe tenqth of the seker addB.on.kfdr 6nst void *bofi size_r buften).tut . 45. ? Aconnectronte* pbces (process uslng UDp) issues rhe reryfrom system 6llto recelve from inmmlno queue. so. Nonally it rs *tto zero. the datagEmssend by a remote prcess. The tunction €turns the number of .e$. buf ts rhe potnrer to tie b!trer wherc the dara wlll be srored and buflen deffnes the te.ddrten). Explaln wrire .d.and -1 if there ls an erbr.ocktd ) i The scket de5(iptor is not valid afterthis catl. How . $iz.ds iftherc rs nc eror and 0 otheeise.nd -1tr rhere is a1errcr.tton.grh ol the buffei Thls tunctlon Eturns tie numbcr of bltes ecetved tf su@$fut. returns an Prepar€d By: rvtre.ize_t recvfrom(lnt . 6n.ockfdr .O lt end- or-file @ndltron ls derecr.t(lnt .tde. nt ct os€(int . socKd is rhe s@ker dscnptor.

ofrmunicarion to whrch a nafre . so. . a process Pr€p5r.d ay: r!8.e$ a seryer Gtted concurenr 5etue.t isa Dar.lfy tne So.ntseruer? Asetuer running infniretyand accepting conne.ker abstracrion? (DEC 2OO7) The socket is the baslc absrractlon for network.tn_addr. wh. which malnty hotds an rp addre$. *r to zero lor TCp and UDp.defines the prorocot group TyPe .ket Poto. a structure of rype sockadd ress.rions fr6m.ate wtth each other. lnJrort_t . Local $cket address detins rhe leat ectet address. Two proce$es need a socket at each €nd to communi.trLrorq . which in rurns gtves rh€ iesource form other server ca ed itehriveseNei.ln_z. seruer? If a client reqoest to a seNer for a esource. n8s1/ NErwoR'( pRoGM _!!I:L E e_trmlly_t . I ulnta-t .ddres.tructitr_addr . what is . The structure has five fields.n by so.in_famlY.ol . .ot suire ned a structure 6lled a socker addrss.. Saravanan AP/IT. The socket vatuesa : Spe. 51. Famlly . It is an end point of . e Th€ ommunietion sttocture used for socket prografiming (DEC 2O11/ 2012) isc[ed ecket.defines the type of so. 0 ior sleess and -1 tf any effor.tients is catled a Darent seruer.ommuni.lrent[ be bound. . F 49.ation in th€ > Defines an endpolntofcommunicauon fo. MEc .am rhar use the TCplIp prcto. strucr sock. what do you me.deflnes the remote socket addressl a skucture of lype so.Be? lf many . s.r u re? The applieuon prcq.ket Ad d ress 6tru.on. What rs iterativ. P.har . Artheeswan ap/tT.urrent s. t4Ec l4r.

@.ocldd. eture..tated with a ecker. s. lnteoer.l.ess ls.€rn am.: Retum the locl protocot add@s asociat€d wth a so.tton bindsaskettoa to@t$cker address by addlno the $cket addls to an alr6dy c@ted $c.( i nt so.kaddE.ka.eeds to cal the socket funcuon in order to use the rerumed lalue as rhe socket d6criptor. structso.kaddr *peeraddr. sS. Expl.k t . tt*". loGladdr is the pointer to the $cket addrss ofthe loclmachlne a. S.ker.ockten_t *addrten).lany request are poces*d 1. NtEc .oGt s.ataddr. siall lo.t. so.e of bind O syrt m ca[? The bind tun.. sockfd is the ecket descrtpror. the clent nEt. P.kt..IT 2351 / I{ETWONX PROGRAX IIIG AI{D IIAI{AGEMENT UNr.1 > Opedting systen malntains informarion about the socket:and its > Appli6tio. Thts function *ts values for the loctsock€t addres.i f.(lnt so.ln th.to6taddr. 1r rscalled when thenme When the timetaken to complete talen to completed the the pro. i.knam.6o. int |4ost $cket tuncflons requirea pointerto a sockeraddress strudu'e 3s an argunent.rauv.o.on. Sa6vanan Apln'. int getsockna m. Both the functions eturns O ifok else 1cn eror.kf4 stru.kt.kfd.rdr * to. ^ (@!or"tmeui.n). IyIEC !rr.r.urrcnt seru.What iEth. One r€quest is prcce$ed:ta 2.n on{ctur€ h bneL Socket Pograhming ro hotd informauon abouttheaddBss and port and other Infomation. bhd(lnt.. Return the remore add. To use rhrs tuncnor.essthls seruer ls equest ls infinite or PEp.ftis tun.hd r€mote sock€t addrc$es be REXOTE AND fOCAf ADDRESS > G.n_t loc.Bo.@s the $cket for seDds.l. *Ner and. Artheeswan Aplrl. u. 0 for By: Mrs.n_t *addrten).ddn.rion returns an succs and -1lf any error.d lo@taddrlen ts rhe tength ofthe tocat socket addr*.6s asso.

rcd By: i46. r.kers Cnn tEnsmit only limited amount can transmit larqe amount of dara sequencing of packet is guaEnteed in h it is notguaranteed that the UDP TCP.ieans the packets thar ae sent paciet will reach in timetothe @ eq "*.kers (fiAy 2orr) "r<Toi"tinsui"lr "i Rellable. Saravanan APIIT. Arrheeswart Aplll tr4Ec PaEeTz Mr.rery orTDoes nor provtde gudE. address */ ). Connection Oriented prolocot Arlides suaranreed det.p.s rransmission connot protocol (fqe) or the User DatasGm prctocot (Uqe). (DEc 2orrl2or2) The well-known port numbeE are the @t numbeE that are resewed for asslanfrenr by the Iiternet corporaflon 60r Assigned Names and Nombe6 GeAN) ror use by the appricrion end pohts rhat ommunicate ushs rhe tnrerner. /fr x( (v oorine wen-rnown pon. P.t*u. t{Ec . 4.n Tcp so. IT / NETX/ORK PROGMM '351 3.k ts ard Uopso. porr numbets o to 1024 are reserued for pnvlleged serures ahd designated a3 welt-known ports. { length of th€ structurc */ addres famrly : Af_ XXX value prcto@l speclfi. Setuer software husr be proqEfrmed expltcttty to t. The requesrcn be ofany complexlty and duratton. thrs lst of Pr. s. (eed de very pacrets lofpa.

Itcan be blg endi. -6 Ddttr. (MAY 2011) r unreliable dellv!ry r h-orde. It is an end pornr of communi. rnr-'neL. . uDp uses a pair of daragEm sockets ro s€nd a messaqe from .ket.II{II{G AND MANAGEI\4ENT be bound.nd . They are stream socket.h betw.ommu.n socket altows processes to communtcate using Tcp/tp. MEc Page 13 l4r. TYp€s of So. for e. TCp uses a palr of so.gua6nt€ed I no ordersuacntees ! no notion oftconnecfloni . Two processes need a socket at ea.par. meaDt by tDst byt€ ordertng? r' HOST AYIE ORDER . IT 235T / I|ETWORX PROGMA.d By ! Ivtts. > oatagEm scketallows proces*s to. $d.tct provtde a@$ ro tcMp or OSPF that direcfly use iie serutes of Ip.lure used for socket programminq is caled so.kets to connecr one appticrion prcqram to another acoss the ln rernet.keb. The @hmunlcatlon stru.theeswari aplrT.i@re using llDp. app lndl@tes dest. Whlt l. The socketvatuesare Ipaddress and port number. > Raw ro. A.nd UDD packet i can send orre@ive r srrucrure is soc( DGRAM 64.aflon to which a name .norltttle endian.en Tcp so.ppliotlon pogr€m to another across rh.. Dl.ket interfa@ defines three types of sockers.tlnggi.ket: The so.1 rell-known po4 numbe4 speL'fre< rhe oo.t out tr.h e. Saravanan AplII. + Pr. 63.ate with each other. s. > Stre. typ€5. It is the byteorderlng used bya gtven system.r.d to communi. MEC .oce$ cs its @. the datagram socketand rhe Ewsocket.r used oy the <eaFr p. P.&6tr .tact port.

tot. > OVERVIEWOFTCP / IP PROTOCOLS Web Clients and Servers. TCP conratns atgorithms to esimate the round t. B F I 'kxetdtn tfi6 TcP lay. Artheeswarl AP/IT. so that tr PreDired By: i4rs. A Tcp ctient st6blishes a connedion wtth the seryer. berween c[ents and seder. TCp provtdes Uow co. qchange dara wlth rhe seryer and then temlnate the connection. associating a sequenc€ number wlth ev€ry by.k on 6therside. FROT Figure | Clent and Se ercommlnicalon on the same Erhernet usinq TCp fCP : TRINSI{ISSION CON'ROL PROTOCOL lcP prcvids connectio. The actuaL ftow of lnformation between the ctient and seryer goes down the prctocol srack on one side across the nerworkand up the pbto.ot.ring in details wirh neatsket. MEC i4r.ate ustn! the Tcp p@ro. rI2351/ NETWORK PROGRIMMING AND MANAGEIIENT UTrI.I i PART .otsta.ommuni. P.lp Uhe (RTT) bebveen a ctienr and seruer dynamiGtty. MEC . S.ty/ tullduplex and al$sequen@s the data b.h.te that tt sends.ot_ TCp @mmunicates with the dara |nk tayer lsrnq lp proto. SaEvanan Aplrr. relabtl.

Once a togtn syslem ts estabtished. TELTIET-REMOTE LO6IN: rhe.: T)]E TCP\IP StANdArd prcto@l for transferins eledronic messaqe from one machine ro another nachine. SMTP-SIMPLE MAIL TMIISFER PROTOCOI. IT235I / NENVOR( PROGMMi4ING ANO MANAGEII4ENT UNTT.ols are defined atthe top tEyer. lt.ftD dtffer fmm the olher applieuons b*aus. ts use to . TCp always specjfies rhe no.ation proto. This is called adv€nsed winlow. TFTP is UDP not TCp. Either ol thes hvo protocots ere used by the appti. The mechanlshs used by theTEnspod ayerto determine whetherdata has been . Tie @re pbtocots of th€ Transport layer are ta.orectly delivered are: . S. P. DNS -DOMAIN NAME SERVTCET the ontine distributed database system used to map host names Into IP addEss_ . SIMPIE NETWORK MAI{AGEIEI{T pROtOCoL! a protocot use ro managethe devic€s such as hosrs.ode consums te$ memory. routerand pitnte6. 2. Artheeswari Ap/rr. TFIP-TRWIA! Fr(E titANSFER PROTOCOa: it is a simpte f e transfer potocol it ls not @mpld as fiP.I knows how long to weit foran acknowteloemenr.sntssioh cohtrol Prctocol ltcP) and rhe uset Datasran protocot (UDp).es provtded by the tayeE betow. the chotce depends on th€ appll6Uon! rEnsmisston re|abjlity requirements. 6. whtch tfrp ement specific user applieuons and other hlghlevet fundions.t sysrem to srart a Iogln s*ton on a remore system.q the Apptication tayer wtth sesston and dataqEm @mhunlcatron servlces. 14EC . . MEC l'1r.sfer a fite: controt conne.there is no securiry provisions.rcp\rp standard proro6t for remote temhal *ru|@ .} APPLICAIION IAYER Appli.t p@ces pas6 the u*rs keystrokes to the server pbces. TRA'{SPORT IAYER 7he trcheon taver (dlso &nown as the Host-to-Host Transport tayer) rs rsponslble for provdl. 5.lte. it spe. Saravanan AP/IT. the .an be used smal machine .ify how ro mait systems inteEct and the form of controt mssages they exchange to tBnsfer mait. 3.aton layer process.onnections to tra. application Drotocots are ihe oniy ones that do not provide seruices ro 3 hiqher layeri thev make us€ cfserui. trdoes not have much. since they are at rhe top ofthe stack.t on data connection. 4.TELiIET altows an tnteractive use6 and the ctie. SNI'IP. r FIP-FILE iRAI{SFER PROTOCOL: the TCpVp standard proro@ts tur a transferring flte s from one machine to another machine. AckiowledsementresDonses Prcpaied By: I4B. of bytes to be*nr bythe peer.

the socket addEs structu@ must contalnthe lPeddre$ and po.4MING ANO IIANAGEMENT The Transport laye r facilitates two rypes ofcommunicauon: ! conn. and oedlum.ct(l. conn. TCPltP was designed to be independent of the network a@ess metnod.t ecldd.4i P.t ils . BINDO .an transmltanv data .25 and FEme Relav.) and a.<Ey!/Eocket.. I!eb4o4-]l!e@!e--ral!5..ddr .h as Ethernd end Token Rlng and wAN technoloqi€ . l4EC . TCP is a more Eliable foro ordata exchanqe than UDP.lln.sMdd. MEC Page 16 I.t m ellr in d.t ditrerins n€twork types. frame format. o seNaddF pointer to socket addres structure .. In this wav.all systems do not need to etabllstr a @nnedion with the r€cipient pnor to data exchaige.uch . Independene ftlm any spe. accEPT0 > r!!Elg9!!EgEt94!!i The @nnect tunctlon b used by a TCP client to Btabllsh a @nnectlon with a TeP .onst 3trsct . Artheeswari AP/II. sckle. Saravanan AP/IT. stelllte links.lfic network technologv glves rcPlIP the ablltty to be adapted to new technoloqies slch as Asynchrcnous TrEnsfer ode (ATM). A connectron must be established at the Transport layerofboth systems befoE the applicatioi. LISTENO . ExDl.ln the aollowlng sy.lud.-LAIEE Ihe NetNUk lnt4lace /ays (al$ 6lled the Network . N UEIu9Bf. CONNECTO .@$ methods such as csi4A/cD (6rler *nsed multlple ace$ wlth @lllslon 2.tion-oriented ocP) ..-t o sockfd-> ecket descrlptor value. TnE layer include IAN technoroqies su.dorl6s (uDP) .t numberofthe server.kets on the network medium and @iving TCP/IP packets otr the netuork medium.s X. PrcpaEd ay r Mc.(C6 laver) is responslble foi pladng TCP/IP pa. O DAIAUI{ !4XEA It of comblnation of datalink and physlcl layers that d€als wlth pure @nsists hardwa€ (wlrs.IT 2351/ NEaWORK PROGRAI.h> int conn. etc. TCP/P can be used to conne.

Addrlen.kaddr *my!ddr. i4EC t1r. temelchooses port Prcpared By: Mrs. saravaran aP/Ii.ddrter)i .tden t . EISCONN r the so. bytes.ockt t.hooses IP address and port Kernelchooses IPeddre$ and pbess specifies port Prccess speclRes lP address. S. p. II 2351 / NETWOnX PROGRAII'.The size oftne.ket is. EIITEDOUT Ilthe @nnecuon is noresrab shed If the port number specfed is not wait n9 on the seryer for whef the desnnation islnreachable lrom some inrermediate BII{D FUI{CTION: ' The brnd funct on assigns a tocatprcrocol address to a socket .or. so.ddr6r rtruc1ure r. t4Ec .1on ermr.ddress or 123 bits tpv6 addBs atong with a 16 brts TCP or UDp port number lnt blnd(int . Artheeswari Aplrt. .t returns 0 if OK & -1 on errcr r so. .r 3truct s.{ING AND MANACEMEM o ddnen-> iJengrh Notava d socket descrlptor EIIOTSOCK If the fiBt argument ls notspecified.sockct d6cnption r !1y addr -the address ofa sttucture rhat spectfles an ip address. Ifthe address is akeady bound to it. EcS!!-Eo!lg Retum 0 tf sucstul &. Not a valld socket dscriptor ffthe nrst argument rs not specified. irternet protocot addre$ is a comblnation ofeither 32 bit IF4/4. If the ocal address argumert polnter Kernel. .kfd.nd port number.lready @noected.

*lnclud. ltrt !r.rlptor Clraddr> client IP addc* Prepared sv: ME. <3y. -r on em' tv o -s7* The kemel mahtaiG two q@u6: It @ntahs a. nuhber of @nEuon the *emel sh@ld queue ior thls alnctodc <Eysl.IT 2351 / NETWORK PROGRA'. .h> lnt .ldd.kros).ddr.o. 2.tion qu€ue. The accept is @lled by the TcP server to retum lh€ ndt completed onnectlon trom the front of the . r rr rerum o.4MING AND MANAGEMENT Pmcess spedfie the IP adde$ &port THE L*'IEN CA[I: It C called only by aTCPse er and rt perforos two functrons. Adn€wan AP/ff.ock t. The seruercan transfer dsta on rhe new sdket afrer finlshlng ihe se er . .5lE of h@mhg @nnectloo request- Not a valld socket de*rlptor r tne fiBt Ergufrent is not speclfied.lnct soct rldr *. It spectRe ttre muinr.socket dscrlptor Backlog. Accept . P.t sockfd.o. Complet€d connedlon oueue: ft@ntains an ent y for eadr cllentwlt1 the Tcp three way handshake has s@kfd.omplet€d conn€.la. + Non neqative dscriptor it Ok t Else"l on errcr sockfd-> ecket des.€at6 a new socket and Eturn the descrrptor of the nesectet to the.ddilen).rox.kl€n-t . The llsten tundlon @nverts an unohnected ecket rnto a passiv€ socket lndloung tiat the kemei should a@pt ihe rncoming conneciion request dlreded z.los rt.aller. 1.h> ht ltd. SaEvanan APIIT./. ent y ior each sYN that afilved fom a clrent for whrch the se er ls awalting @mpletion of the three way (int $. S. MEC Page 18 Mr.@pt (l.t r. i4EC .

ket d es. Thelr @mmunl@tlon net}|od 2.4. MEC . The hfomauon tlEy mahtatn{state t6 d st te tull).rn o"*€en th€ irer. Seruer @n be dasified b6ed on following 1. Allinformatbn aboltthe request must be pla@d ln allmesges Prcpared By I Mts. a cotrn.**". Nol a valld so. This is s@port€d only in stEm. A setuer w5its for r€ads and pEcesse a clients requet aor a se *. P.rlplo r ENOT. (6nn*don 16 d 6nnecfrmqtsta'd). socket is not a socKET sIREAI. Prcvlde rcllable tEnsport t S€NeEarcsimpler t U* a *parate socket for each connectlon.don orlsld smE: .atlve.r rnd > lIEiAflVE SENVER: A seruer is a pro. artheeswari aPln. > clDDCggOEleS!-EltllEi t Us UDP for conne. MEc Ir4r. B. Does not maintaioany iniormatlon Eboutthe outqoing intedctlon wlth Requires long me$ on rheir eNie(iteEtive or @ndrent). Saravanan AP/r.SOCK If ihe fiBt argument is notspecifl€d.n offe6 services. sew. Il 2351 / NEIWORK PROGRAMI. @ yp.IING AND I4AaIAGEMENT Addrlen-> length of:he *cond The connecred ecket is co*c each time while the listeninq ecket emalns open for the llfe of the setue. Does notguadntee Eliable transport t The se erand cllent are 6mpll. Us TCP for mnnectlon onefted mmhunl@tbn .ess whi.tiv.tionlss communi@non . 3. s.

Artheeswad AplIT/ MEC . reruer i4anv eauestare Drocesed ata I one reqJesr r po(eesed dr a Lme Prcpar€d By I r4E. ... client waits for alt p€vrous Equests to be pocs€d. r It lssuitable for empte sefrrer sro as nME se rc. n r35r i NFrWORT PFOCRA .4. Iterativ. > Statefut serven t Maintains information about the status ofthe ongoing tntormauonrith the r l4aintains few infoimarion between request. P. s. Iris notsuitabte when rhe seNce flme.4bytes. .-"-. or seauenttar s.Etiv.tientar a time. INIERNET r The li6t dientrequest to set a fiie of size 2oo r.pefr ' An lteErive setuer*tus singte. terminates abnorma[y. ! It is surtable when the *ryt@ time for each requst is sma[. It rs easierto design an. .tienrs ar the s€me Ume in paraflet.Net ls @lle. Requires sharler n'essa9es. . saGvanan AplrT.J a fuhcurreht setueL Concurrent Vs ft. Is unretiabte ota connedio. and this rype of a s. . .l imptemen!. t Handlesone requestara uhe. The se@nd client Equesrs to qera fite of20 bytes between the 2nd cti€nr has to wair untii the procssing ofctient ends_ > CO CURNEiT' SERVER t A $ruer cn handte huttipte . MEC .

if strinq was vaid. orvarious addre. Server software olst be programmed explicity to handte seryeris locked whlle dealinq with a Dl.add rptr).ary nework by.urs the synta. > Returns 32 bit bi. stru. IT 235I / IiIFTWORX PROGRAIT'MINC ANO II4ANACI I'ENT When the trmetaken to comptete rhe process is less thisserverls used. It. P.s 6nve ^@ . fte equest cn be of any @mplerity and duraiion. appREss There are two or. MEc ?aAE2i i4r.t tn_addr .theeswari aplra.ticat isue. r.ter: t include <arpa/inet.4EC .te ordered rpv4 Addre$. s. It returnsthe 32-bit btnary network byte oder vat!€ & INADDR-NONE it ln_addr_t rneladd(consrchar*skptr).aEder srdnq (dotted decJmat shng ) polnted by srrptr into tfie 32 btt btnary net{ork bytes ordered value which is storedthrcsgh potnreraddrpti o lf the Eddrpb is a nullpornterthe fuhction performs rhe conveBton but does not store any result.onverts 32 bits binary By: Mc. A. Applrcable for both IpV4 & tF4/6 address. saravanan APIIT.uDs ofaddress conveEion functio^s: '004) L net aton. net addr& inet_ntoa : convelcs b€tween Ascll strrnq and network byre ordered bin. o Th€ tunctlon rn€Laton @nverts the d. appticabteonty for rpv4Address 2. / Convcrclon berween ASCTI sHn$ & n. inelpton & rnet_ntop : convets presentauon to numeric &numencto presentation. coitvERsro FuNcrrotrs: (ilaY @. INADDR NONE ifan eror.rwork byte or. > Retums 1.h> int iret aton(@Gr char* strptr.k byre order€d rPV4 address tnro rr5 corespondingdotteddecimal s$ng&rerurn poinrertodotred d*imal Prep..ry vatues.

en presentation and numert. S. .rI 2351/ NEIWORK PROGMI.tion 32-bit binary lPv4 address mapped or lPv4 compatlble IPv6 Address or IPv6 Address Prcpared By: MB. P-> PresenraUon .Retuh pornterto resllt len -> sla of the destrnatron to pevent the tun.Arthee an APltT.r. const void *addrptr.ket addr structure requrring the@ller to know the lomet of $e structurc and addlls fdmily.d6n from deridl.pEed. 6n5t char.har *iret ntoD(lnt familY. const. 16 bit . void.addrptr). Family .4 / Conv.ted and st6ed thbugh It converts rbm numedc (add. IPV4 . IyIEC lrir. To solve this we use G.: These are lsed for both IPV4 & IPV6 addre$.lon betw. saravanan AP/II. ASCtl srring n > nun€ii. I4EC . .strptr. lfthe famrly is not support€d it r€rurn the errcr -1set ro E .q the 6uers buffer.ptr) to preenrarion (strprr). binaryvalue int Inet_pton(int rdmily. I'{ET_ADDR5TRPIR IPV5. The addr is nolmlly ontarnedin a e. P. The dotGd decimal shin! stored ln shptr is conve.n. hN. 0 if not a valld p@nhtion fomat. . II{ETSJDDRSTRPTR '5helntop is it EqurB the cller to pass a polnter to a binary The preblem riBl addjB.AF_INET ilPv4l aF_rNEr5 UA/61 .6l R.

6€n be represented in LSA 00001010 00010111 00001110 00001010 00010111 00001110 a+3 DEC VAX Compute6 Intel lllcbpb. Big Endian Byte Ordedxg r' LITTLE ENDIAN BYIE ORDERIXGI LSB nr Low ord..esl hcreasinq Memorv Address 10. rI 2351 / IIETWORK PROGMXMING AND i{ATAGEI. Utite End an Byte orde.inq 2. s. Artheeswari AP/fi.1 @n't" ""te on uvt oracrins run. MEc rllr. lncreas nq Memory Addr€rs HIGH ORDER BYIE Prepared BV: r4B.g address.e$o6 BIG EI{DIAI{ EYIE ORDERINGI High order bytesorMSBas the starti. p.lAY 2OOa / DEC 2012) i) BY'E ORDERING FUNCNONS The btt6.rons. (l.23. saravanan Ap. byLes as Lhe rra r -q dda. memory tn two weys 1./Ir/ MEC .IEI{I be srored l.14..

par6d By I i4E. el*lr (un.6 can be rcpre*nred in 32 bit as MSB 00001010 00010111 00001110 00000110 00001010 00010111 00001110 00000110 Addes A A+2 A+3 IBI'i I'iainframe ComplteE tlotobla Mi@pltesE /* pDsdh to find host byte order */ ht main (int arqc.s=0*0102. ft is tle bt4e orderins used by a given system...ciol==2 && un. S.ctll==1) 7 TYPES OF BYTE ORDEN BAS€D ON BYIE ORDERTI'IG FUNCIIONS / iIETWOR-X BYIE ORDER . Arthe$ari APIIT. Pr. SaEvanan APIIT. Networkl.I1l.40l==1 && un. CPU-VENDoLOS). un.. P.g prctocols @n choo$ thek own blte otder .=2) c'-')'". i4EC . TCPI1P has the big endlan system. c('::ol r (sl@(sholt)-=2) - { WW\.IT 2351 / NEIWORK PROGRAi4I'1ING AND IIiANAGEMEIiT 10. alol : c)' pnntr C%s".23. char**argv) { €harclsizeo(shon)1. Dnn60brs endran"). ) un. ! It@n be blg endlan orlittleendirn. MEC P1ge24 Mr. r (un. / HOST BYTE ORDER .14.

t4EC . Frcn nost to byte or.ction orleht. It pbvrd$ a rellable data stream a5 tt ensures the sequenual transmi*ion ofdat:.Uon device before data can b€ sent and hence a vidual li.k ls establrshed between sender and reeiver. Artheeswari Ap/rt r.ln th. P.t32bttvalue)i returns value in networ& byle order . Conn*tlon Odented seruicG r Connectlonle$se ices > By: APIIT.IT 2351/ I'IETWORK PROGRANiIING AND fiANAGEMEITT UNIT. . E pl. htons .4Ec Mr. !int32 t htonl(uint32 t ho.1 / AYTE COI{T'ERSION FUI'ICTIONS: . S. This process is alled handshakina. +----!- I r6bir | | 3i bi.sarava. Typ€6 ol serures? .d€r .ln connection oriented method the po@ss starts from the serder computer by sending a request to start the tEnsfer that ls to be acknowledged by the destin. host to netwo* shortU6 btt tnrl t htonl host to network tong t32 bt ntl ulnt16_t hrons(uint16_thostl6bitvatue). I 6.rervtces o In connsuon orlented method sston t5 created betore transmittinE dat6. retoms value in h6t byte o. Prep.d and conne.etwork to host short [16 network to host lonq 132 ntoh(uint32 t #32bitvarue).ter ^etwork .rlontcs.

n eirher be imDlemenred rn the data lrnk raver or rn the transport t:yer. Bur ln @nnectlonl€s romfrunictlon there's no need ofa. Tcp provides a onnedioi.less kansmision th€re is no need to estabtish connectlon.oriented o In connectio.onneclonte$ In onnectloo oriented communlGtion oneu* qulded m. tt atso naned as wrcle$ @mmunloton.ot provide the same reliabllity as offered by @nnetion{nented nethod.rWORK PROGMi4I'1ING AND I\4ANAGEI. rn thse networks there ts need of maintahtnq the state information for the sender and Eeiver devtes rhar.I o After that data is transfercd sequentiaty by proces:. However the speed or cofnectionle$ letsrqLE is better than tho* of connedion. These technrqu$ are lsed ln the lrol!|cff! netwo*s.rT 2351/ NE. Saravanan APIIT.ortented ones beouse they do nor prcvide tow contrcl and errcr deredion.dlnm.abte. u9P provids . Artheeswari AP/rl. The sender lust starts transmttunq data thats why it 6n. i4Ea . MEC PaEe 26 actnowledgements.ks ae us€d to provide etror detecrion_ Th6e hethods c.IENT UNTT. rffin T S. Stiding window and Stop and wait are lsed to trovide flow contro and Cyctic Redundancy Che.s why ir can onty ofier a smalt number of se ices.

Type . cralii. 1.haddr *s.bout $cket.14Ec .tion is. socklen-t r sockfd-> socket descrlotor value.dtddr. space > rrE-t9llEcrcAlE aTcPclientto establish a @nn€ction wlth The connect tunctlo. listen :nd aeept lun. . Sariva. AF INE PV4 Protoco 2. Addren-> Lensth ofhte se er address. .stream Socket (socK SIREAI'4) 2. 1.lnt prctocol).t.specitl€s ttre sockettype. servaddr polntertosocketaddress svucture. ls used by a TcP *irclud6<sys/socket.h> lrt @nn€ct(int so. t Retlrns non necative desc. Raw Socket (SOCK-RAW) used for both TCP & UDP Pemlsbn io @ate ecket ls denied The s'stem has no available buffe. int type. +in.zn APIIT.IT 2351 / I'IETIXORX PROGRAI'IMIIIG ANO MANACEI'4ENT 7.. AF INEI6-IFV6 prctoco .tion. s. P. the socket addr€$ stBctu€ must contaln thelPaddress anc port number of the . Family . .h> int socket(lnt famllv.l) 3. Artheeswari AP/IT. ltlEc r"l r. Dataoram Socket (socK DGMl. 6nnG.tddr@rst struct so.lude<sys/sotket. (DEc 2012) > E9!!EMqEQXi The tun. bind.alled to create a socket to perform client seNer applictlo. Pre?ared By: I.iptor if OK.specifies the protocol family.4rs.

o.tbn rs notestablished Ifthe polt number specified is not waiung > BINO FUNC.lddr @nsi stru. o It returns 0lfoK& assigrs .aady conn€.hoors lP address and port rernelchooses IP address dnd pm.rtption o Myaddr -the address ofa structure that specifies an ip address and port o addrl€n. Retum 0 if su@stul & 1 on errcr. lfthe socket is alr.ted. IT2351/ NETWORK PROGMM * F Not a valid socket descriptor If the firet ar9umentrs notspe.ddr *myaddr..ol addr. local pmto.d. Arrheeswari By I i46.t. P. etror GBADF not a varid so<Ier dsnpbr I ENoTsocK I r the first arqument is not specified. MEC . ETIi4EDOUT lf ihe mnne. v. S.1r.. (ernel.The srze ofthe address structure in byt€s.ld. EADDRINUSE llrtxe add6 is already bound to it. internet pDtocol address is: combrnatron ofetther 32 bit IPV4 address or 12a bits tPv6 addressalong with a 16 bltsTCP or UDP poft nlmber lnt bhd(irt 6o.ockl€n t.!* orth. EFAUTT I rthe lo@laddEs aEument pointer is invalld. Saravanan APllT. kernelchooses port io a socket.n).lr mo lc. MEC Page 28 1.o specrns port Proess specifies IP address.k.IIONi The bind tun.socket des.

MEc Ivlr.t arived arofr a client for which rhe erer rs aMiring @mplerion of tne tnE My handsh.d dne. It specrfies the maximum numb€r of conne.tior the kernetshoutd queue #in.truct sock ddi *.ktos). 2.y. The ke.. Codol€r.klog.tton fbm the frcnt ofthe completed cofnect on by the TCP seNer to return the next completed conne. MEC .lladdr. The listen fun.: It dEi6 4 6Ey for ech drent wiur dE TcP dle Ey handshake ha @mol€t d./sock.nel malntains two q!eu6: It @ntaiE an envy for ech s.rN th.o.tt4 i. *includ6 <sysl.. socktetr taddrten)i t Non negatTve decriptor ifok So. s6*ff. Preparcd ly r sock€t tnto a passtue socket indiGtrng that the kernetsholtd accept the tncoming connecrion request direcred ro this socket..lg mnedion rEqueL Not a €lid sock€t denptor ENOTSOCK lf the flBt argument is not speified. Saravanan aP/r'I.h> lntE. P.kfd-> socket desdlDtor ClladdF> clientlPaddres Addrlen-> ength ofthe sec. Ac. Artheeswarr APlrr. > rHE AccEPT FU CTIO ! The accept ls . The sefrer can nansfer data on the new socket after fintshing the *ruer ctoses tt.h> ht listen (lnr.tude <.ocker'.epr creates a new s4ker and Eturn the descriptor of the new socker to rhe @ller.uon converts an unconne.tba. -1on eror.tfd. a. b. t It eturn 0 ifoK. s..iENT Proes specines the Ip address & port > tHE IISTEN CAL[: Itis called only 6y a TCPsetuerand t pedorms two (lnt so.stse of lli@mt.IT 2351 / l{ETWORX PROGRAIIMING AilD IIANAGET.nd argumeit.ri6n outu.$det deiptd A.

P.Artheeswan aP/IT.&ettunctions requtred slngle. socket rs not a socKET STREAM. s..le the tisteninq socket remai. Expl. l4EC . If the nrstargument is not specified. with the h€rp of a frow chart luncilons m:y b€ used.sopen for the life ofthe se&er. yErphin the v.riou. Read IISTEN( socKET( ) crasE( ) READO crosEo PrcpaEd ay: Mrs. Saravanan APIIT.ted onty i sneam.T 2351 / IIETWORK PROGRAMMING AND i4ANAGEMENI UIIT. This js suppc.I The connected socket is closed €ach time wt. tlEc i4r.Per Eg!!{t.. so. Not a va d socketdescrpio.

specifis the socket type. P.t st.ket(int family.t pbtocol 6slqE a addlE ls.ddrl.ddr. aclc4rsds Return O if su(estul &-1on etror. 1. . Returns non.atlor. MEC . r the protocolfamily. *ln.Raw Socket (sOCK_R^W) . Gmbhanon of elther 32 bit Iw4 addEs or 124 bts lPv6 addres. Peml$ion to @ate s4let I5 deni€d.The size ofthe address structure in bytes.IT > SoGIELEU!. Sa6vanan APlrT. int typ€r intproto.rT 2351 / I'IEfWORX PROGRAMMING AND MANAGEMEI. l-Stream Socket (5OCK_STREAI4) . The blnd tun tion l@l pbtocol address to a socket .lonq wrth d 16 blts TcP or UDP port number I blnd(l $ctdd.u.n). 6tr.4) Used forUDPConnetlon 3.h> int so. Prcp. AFJNET6-IPV6 protocol ' Typ€ .eqative dscnotor lfoK.socket descrlptlon o My addr -the address ofa structure that speciflB En lp address aod 9on numb€. MEc Mr.le<sys/so. AF INET TPV4 prcto. o Addrlen.set to 0.U€rLt . Used for TCP Connedion 2.ed to crate a socket to perform client *ryer appll.U*d for both TCP& UDP &ICMP. . Family . sockad. intem. .red By ! t{6.o.ol 2. Artnesw.t so. 5. The system has noavaitable bufrerspate.ol)..SI!9!! 'I1le tunction is@l.ket.rr .Datagram Socket (SOCK DGMI. .

iia ay. v^ s a. _1d em Tie kernel malntains tm queu6: 3.dbrjng that UE kernel should a@Pt the lncominq connection requ6t dlEtld to tnk sket.ompleb onnedion du4e: ft @ntaiE an entry for 6dr sYN that anived from a cllent for whlch the se. In.g). P. lnt". caodelrd @on!cl9!-sul1rei It contahs an €ntrv for dci clle.t witn the TcP thEe sav handshake h's completed .Ir Z:ST I NEN.onnection the kemel should quae for 2. ffthe address l5 akeady bound to it. kemelchoose po't Pro@s specifies the IP addEs & port > THE LIS. It spedfie tne mdlmum nlmber of .socket dEcndor Bacldog_ slze ofln@mlng connectlon request 4 !*. <5r. addBs arsument pointer NESUIT Kernel choAs6 IP address and Port (enrerchooses.tEd $cker into a pa$lc scket I. rfthe lc.GLh> lnt lltar (lnt 3drdd.o.d lt p€rfoms two tu.^/ORK PROGMM ERRON CODE Not a valid solketdecriptor rr e fiBt arsu. saravanor APl'T 14Ec .4r.entIs notsp€cifled. MEc .r aPlrr..IEII CALL: It ls 6lled only by a TcP saruer a.swa.Jer is a{6ldng ompletlon of the th@ @v h'ndshak€' 4.Pase32 I. this ec*et. sdkfd.cldr.ctions' 1.Paddress and proes epectrrE pon Prccess specifis IPaddEss. The t6ten tunctlon onverts an un@nne./. t It erum o Ifox.

Artheswari AP/Ir.n).ddr +. MTNG AI{D MAIVAGIT4EN T U TT. Thrs E $p9dted only in steam ilot .h> t a. But TCP wlll try to send any data that isalreadv queued to be sent to the after thrs the normalTcP coinection termlnalion sequene takes pla. v. It return 0 ifOK . s./.ept (irt s.rrptor if oK satfd-> *ket d6olptor dladdr-> dlent lP addlE Addrten-> lsEth of rne snd The d. Saravanan APln. t Non neqative des. -1on eror. .er finEhing the rede' rlotss lr.kfd.e PEDared ay r M6.lld sd@t d6olptor EI{OTsOC|< r tne tct aqument is not sp€'hed.v. socklen-t rddrl. IEE4CeEerEUtggell The accept iscalled by the TcP sere. MEC Page33 I'4i P. .td.h> int. Aaept cr€ates a new socket ard retlm the de*rlptor of the new $. to return the nertcompleted connedion from th€ front of the ompl€ted connection quele. The seruer can kansfer data on the neh socker af.ket to the @ller.&efd). The socket decriDtor ls no lonqer usable bv ihe used as an argument to read orwdte. *includc <.o.los€(int so. tt marks the $cket as closed and return to the . eloslEuqroli it is used to d6e the scket and terminate a TCJ connedlon *h.lude<uni. uE liE ot t E *ruer.k. Else . MEC .lladdr.1 Not a valid ecket descrlptor lfthe firet aroument rs not specifled.k€t. strct so. saket is not a soc(EI-sTRE ll.E t d $det rs ded 6dr tifttn etne listenlngs@ket EmiE ocar lh.

de<EYr/tock't h> lnt 6o.k. clo5e > secrElllllcrlaE Ihe tunctlon ts @lled to 6ead. Saravanan APlIr.U*d for TCP Conne'tlon Socket (SOCK-STREAM) thc modole.Raw Socket (sOC( RAw) .Used for UDP connectlon & uDP &ICMP' 3. with th. soc*€t fun.speifles the socket tYPe l StEn . Re€d 5. MEc Mr. Expl. ! ReLurns non negdnve descnptor ifoR . s.s no av6llable buffer space' ME. ut. Anheeswan AP/IT.tion 3. qam.sp€(mes the proto(olfamilv. lnt tvp'. viriols scket lrnctiors requlEd to lmplement 9. P.d.Ured ror ooth TCP t Pbtcd .'y . Expt.l. MEC . AFJNET5_IPV6 Proto@l ! TYPe . a socket to Perform client s er appli€tton * to o EACCES Peftislon to cEte socket is denied The system h.t(ha famitY. h'rp of a flow ch:rt tn' scqu€n'€ functloG m. AF lNET-lPv4 Protocol 4.Dataq6m Sock€t (soclqDcRAln) . 3. The tunctlon calls nE 1.Y b. ht DEtodl).

Socktd-> socket descnptor vatue. . Saravanan AP/IT. MEc PaBe 35 Mr. MEC . the socket address structure mustcoitain the IPaddre$ and port number ofthe ' addrleh-> Lenqth o lnte setuer add./uket. P.h> lnt @mect(aot $ stru.ture.eru:ddrr sockt.r_t .t so.haddr *.<ry. Prcparcd By: MB.IT 2351 / I'IETWORK PROGRA'.IMIiIG AI{D MANAGEMEM ' socKEr( tus. s. ServaddF pointerto socket addrGs stru.l l socKET( ) CoNNECT( ) Blocks unulconn€ction WRITE( l closE( ) > THE OOX ECTCALL: The connect functlon is us€d by a TCP ctient to *rabtish a connecrion with a TCP *hclud. Artheeswari Ap/lT.

ted tne.lem'nt'rv TcP lutctloB wlth Expt. fte client sends a reque* ro the seryer lne client the rcqu6t and tne *nd back a Eplv to the client' This dntinues until to th€ ct6es irs end of the connedion whlch *nds an end_of file . MEC . s. i[-oma gviii."sdair AP.*.e(ht sockerd). I'aEc Prse 36 Mr P s:ravanan aP/tT.lude<unBtd..otifiGtton then dos its end of the connectron and either tetminates or sder.t'.wnte to be *nt to the But TcP wlll try tD *nd anv data that ls alr€adv qu€ued . ur.m.r.t turcdont for .l TcP @nn4tjon lemlnation *quene takes plae' p* Alter ln d.lfT-1 23511 NETWORK PROGRAMI4II{6 AND I'4ANAGEMEII r. tt Ptlrn o if oK Itmarks the sock€t as clGed and return to the pbcss lmm€diatelv' The $cket de*rlptoris no longerusable bv th€ pb@s .Lll th. The *Ner (alt5 lor a ns client@nn4tlon. sometin€ later a client is started that the seler pro(e* @nnects to a seru. . is unEachable frcm some intemedlate CIOSE FUNCTION: rt is used to close the socket a nd terminate a TcP corn4tion' +i6.In ' SCEIIARIO BETWEE fHE CllCI{T AIID SCRVER: FEt the seNer' is sta.r. a. EISCONN tf the socket isalreadv connected. .iting on the setuer for when the destlnatio.. tl s dP nom. EIIMEDOUT rf the @nnection is not establlsh€d If th€ port number specjfied is not w. it be 'annot used as an srqument to ead o.h> intclo.t a valid socket d escripto r Il the firstargsment is notspecified.

i4EC I4r. 1. P. 5.used for both Tcp & uDp & rcMp. PEpared Ey: l4rs. MEC .StEm Soclet (sock_sTREAI. intprctocot).sp€cifies the prctocot famity.o.Raw Socket (Socx-MW) .4) . AF_INET5 rPV6 protocot Type .ket(inr famlly. Retums non negative descriptor if OK. #tr.DatagEm Socket (SOCK DGRAI4) . S. SaravrnanAP/fi.used for rcP connection 2. irt type. IT 235T / ftETWORX PROGRAIIiIING AND IIANAGtMFNT UNN-I socKET( TISTEN( SOCKIT( l CoNNECT( ) wRlTl( ) ct osE{ ) ct osE( ) > socxEr Euracllox: The tuncuon is dlled to . Anheeswari AplIr. Fami. AF IIEI-IPV4 protocol 6. Used for UDPConnection 3.reat€ a soCiet to perform ctient s€ erapploflon.y .tude<syslso.h> int .specifi€ the socket type.ket.

Permiision to .n). intemet pbto@l add6 ls a @mbinEtion of €nner 32 bt tPv4 addl€s or 123 bats lPv6 addlEs alonq wlth a 16 b'ts ICP or UOP port numtcr irt bind(irt $cldd. If the add€s ls already bou.klen-t .!8.N / NETWORT R. I I EIlLEUlgUalr the bind tunctlon a$rgc a l@l pDtc. Sa6vanan aPllI. Prcpared By: l. l'4Ec .II'4ING AND MANACEYENT UNII'I '35I Prctocol.socket decnpnon o My addr theaddre$ ofa structure that specifies an lp addr6sand port o Addrlen.turn code: Rerurn 0 if su@sstul & -1on erbi Not a valld socketd6criptor ENOTSOCK If the fiEt argument is rot speclfied. Kernel choces lP Eddress and port net ct ose Ipaaaesuna poesssp€cifies Port Poces sp<lfis IP address.ddr.l addE5 to a sd*et .set to 0. ft€ $stem has no avallable bufrer spa. S.e. ilEC Mi P. kernelchooses port Pro@ss specifies the lP address & pon > I!!-!EII!-c4!!r It is 6led only byaTcPse erand it p€rforms twofunctions. @n3t 3tr!d *kaddr .d to it lf the locladdress arqument polnter is Invalid. Atheesari AP/IT. o It Eturns 0 if OX & -1on e@r o socnid.rea6 socket is denred.Th€ size of the addres structue in bytes. *.

> THE ACCCEY FUI{CIIOI{: The a@pt is @lled by the TCP e er to etum rhe next @mpteted 6nnd. Thts ts supported only tn stEam. Completed 6nnedion oueuei It @ntainsan entry for ea. The kernelmainteins two queues: 5. S. &det d@iptor Backlog. p. The listentun*Dn mnverts an un.k.ockten_t .non eqne.ompleted conoecuon queue.h> ht ll.ten (int . rhe servercan tr. Ihe @nnected socket is closed each ttinewhilethe ltstenjng so.ddr *. Saravanan AplIT. htbacktoq).k Lh> int . . -1on errcr.ket remalns open for the litu of the seryer. <sys/3o. In@mplete 6nn€dion oueue: It. Accpt creat€ a ner socket and Eturn the descriptorofthe new socket to rhe caller.o.ept rhe incomrnq.size of tn@mtng 6ne.4EC Page 39 r. a. Artheeswari Ap/IT.n). .onne.onne. It retlrn 0 tfOK.nsfer data on the new socket afier fintshinq the s€ er closes it.IT 3. t Non n€gattve dscriptor rfOK t Else -1 on eror Socktd-> socket descriptor cliaddF> client IP address addnen-> ehgth ofthe second arlumenr.4r. PreD. 6.kfd.ompletlon olthe three way handshake.tI 2351 / I{ETWORK PROGMMMIiIG AI'ID MANAGEI'4EI.cccpt (int Eocldd. ftspecJfies the maximum number otconnecuon rhe kernershoutd q!e!efor sin.h ctientwirh the TCp three way handshake has Socldd.rected to ihls socket.lud.Uon from the frorr of tlre .rcd Bv: M6. Not a valld wket dediptor r the f6t aqument is not requesr d.k€t..ddrt. l.ied socket tnto a passtvesocket indictlng that the kernel shoutd a. struct so.lude <sys/so. #in. MEC .ontains an entry for each sYN rhat artved lrom a ctient for which the sererls awaltinq.a.ddr.

MEC .yslsock.4rNG aNo r4Alg-y.d!dc<untstd'n> ht clce(lnt $ctcfd)i It marks the sodGt as.tlon is unreach6ble ftum $me lntermedl'ie > crrosE FUI{CIIOX: ft is used to de the so.g Not a valid ecket dedlptor ENOTSOCK rthe firet argument 15 not specified..iDtor rthe fiBt argument E not specined.t.edtundlon is used bY aTCPcli€ntto establish a wlth a rCP 'onnection *in.din. Sockfd-> so..dptot value. o El*_1one or .orst3trucl.kel des.. s adheesan AP/rr. MEC Mi P. ETIMEDOUT r tie coMedlon is not establlshed ECONNREFI'SED If the port number spedned E not waiunq on tie *wer lor ENETT'NREACT when 6e d. . sewaddts pointer to ecket address structure the scket addls . Sahvanan APIIT.ker is nora socKET STREAM.lude<. sttudure must @ntaln the tP addre* and port 'umber of the .4haddt*sd. todd'n-t aildrlen). Prc!. Th. rr 23s1 / NErwoRK pRoGMM.ddr. lf the ecket ls akeadv @nnected. addrl€n-> Lensth o fhte $Ner address Not a valld soclet d€sc.ket sid temioate a TcP connectlon tl. By ! ltlrs.losed and €tum to the pb'ess lmmedlatelv' The socket dsriptor as no lonqer u*ble by the prc'ess .n. lt cnnot be ued as an a4ument to read or wdte to be sert to th€ But TcPwillt y to send anv data tnat b alreadv queued other €nd.h> lntcornect(Int$ckfdt.

t siLfamfly./ /* length of the structle s_fahlly_t sa_family. Comp.32 bitlpv4 address tn netwoik byte orde..IMING AND AIAGEMEMT UNTT. I.. UnrX domair . PrcparEd By ! M6. 11.4Ec rti.r. /.F xlx value /* pret@l specrfic addre$ r/ 7 lDva SOGIET rpDlESs sr rctutE ton) rERnEr soa(Er AppREsS slnucruRE t m. your . IPv5 SockFt Acdress Srru L? / GENERIC SOCXET ADDRESS SIRUCTURE { . . tpv6. /* 16 blt pori'/ struct in_addr sln_addr. tfte rpv4. IPv4 Socket Address Srru. strud $ckaddr in t uint8t sln_lenj /r length ofthe structure */ *_fdmily.$uhptto.6s structure 2. /.lrqdtrE. rr4Ec . /* thusedt/ j'. .hdrsh_zerol3l. s.*/ 1. Cenenc Socket Add. Artheeswan AP/IT.r SOCKEI ADDRESS STRUCTURES ' Each prctocol suit€ defin4 lts own scket addE$ stiuctures. Ile name of the strudure begins wlth sockaddr .\fter this the nomat TCp connedion termlnation sequene takes ptae. P. Varicus ecket address qtrudurpc .T : .iure 3.nd datatink 3o. 32 btt lpv4 addres in aetwork order */ .t t. sar6vanan Apll1. /r addB t mily : .ket address .r. /* AF_aNET */ rn_irorlt sinJ)on. I. N 7351 / NETWqRX PROCRAI. { in_addr_t s_addr.

. MEC PaEe42 Mr. saravahan AP/F. (riAY 2012) RererQ.ll€ni sry6r (irAY2012) Refer Q. in detall th.I / IPI'6 SOCKET ADDRESS STTUCTURE SIN6-LEN /r recutred f6rcomprle nme tesEr/ { /* rensth or the structuB */ e_fanily t sin6-famlly. No.PAIISOX OF SaCXEI ADDRESS STRUCIURE 1Pr4 !86 !J!IX 12. Expl. l'-j. I{ETWORK PROGMMI'IING ANO II4ANACLMEIIT UNTT.5o. Explain .04 13. o.k btte ordered strucr lcP . /* TransDort Laver port in Net{oft Byte order /*Pdonty &flow label in netwo. I4Ec .6 addr i /* IPv6 address in network byte order r/ ).sv.IT 2]5T .ari AP/IT.ket functions lnvolv. { r' @I. in det. .d ln a ba. r0 P-t"*d Ey..onvcrsloD fun. artt".s.ny tiB..

TCP MAXSEG wlndow S6le Optlon .k. The cl. It contEins onty tP Hsderr TCP Header and po$ible TcP optlons..llent TCP to end a sYN (SF6miz) eglrbr to lel tne serye. This 6U* the . neat. l1re manmum number of paclets EqutEd for the exchange B th. > IGE-9eIIA!SI me$age @ntalns TCP options such as 1 2 1.B tlE initirt s.r Socket.f -l II2351 / ITENYORX PROGRAMIiING AT{D MANAGEMETIT UNTT. io.1 14. Artheeswart AP/IT.tive open by ottilE @EE<t. MEC lvr. brnd and risten.kctch.knowtedgement of the cllenls sYN in a srngte *dRnt.ends the a. Tlmestamo Option i Needed ror hlsh sped @nneuons to orevent posslble data corruptlon caused by lost packets Prepar€d By I IvtB. No d.n a. tle clie. a thEe ws H. d$ . hen@thls is @lled as three .ent must adarMtedse tie *re/s syN.ta rs *m with SYN. MEC I . Saravanan APIIT. The * er must a. P.aept an rn6min9 @n6tion.ndrh.t's inrtralsequene numb. 3.nd T€rmitratton wtth. llSS Opnon I Maxlmlm Segment Slze .r€d to . t E data that the clent wi send on the onnectlon. Ttis is normally done by cllins ecket. This is crred as The Client isues. The maximum wlndow size that tae -rcP @n advertise to other TcP ls 6s535.way handshake. E(plain TcP Connectlor BtabliEhment. tne dtents SYN and the seruer must ste *nd lts own SYN drbrr{. Connect (blocks) The se er must b€ pEp. (itaY20r2) r' TCF COI{NECIIOT{ EST ELISHMEIIII.quen@ number for the data that the 5e€ sldi The ere.lrowledg.

o.odct ltow dlagr. erth*rr p/rr.l (fi) cdEllgt$rui (DEC 2011) Refer Q.d . MK . THE seNer *nds the FIN segment to the cllent The cllent acknowledges the aN seEment eeived from se er and frnallv bmrnateE the onnection.ltent@lls close and performs active . TCP sends FIN segm€nt' The seruer ecelvG the FIN and perfofms the passive close.3 _ r"po. The r*lved FIN s acknowledged by rcP.let ll: (D n n rE *r. uo. E)9Lb! ttE noflorlng ln . (DEC 2O1t) Rerer Q.a gy . sarcvdin APlfi. IJNTT I TCPCONI'IECIION TER INAAION : TCp uses four segments to terfrinate the. TcP .nd qplain thc functloB. 15. MTNC AND MANACLIVE . ltc Fage 44 Mr. The. 10 15. o. flo.nection. DEw .lose. s. P.