Sie sind auf Seite 1von 44

DEPARTMENT OF INFORMATION TECHNOLOGY

III YEAR / VI SEM


II 2351 - NETWORI( PROGBTAMIIING AND MAI{AGEMENT

, UIILI
ELEMENTARY TCP SOCIGT
SYLLABUS!

Introdldion to Socket Prcgrammhg -


overuiew of TCP/IP Protocots
introduction to Sockets - Socket address Strlcturs Blte odertng
flnctions - address conversion tunctions - Elemenrary TcP sockets -
socket, connect, bind, listen, acceptr read, wrtte, close tundrons - rteratrve
Seruer - Co.crrrenr seNar,
PART . A
1. Gro!, th6 ost laYers by lunGU.n,
The seven laye6 of the OSI modelbelongrng to thee subgroups. Physical,
data llnk and network laye6.re the ntwork 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 ben 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 frame.an
be combhed intojlsi one frame
a, what are thc n6two* support tayeF and th usef .lpport tEyeB?
Network support tayB:
The nehvork support tayeB are physicat byer, Data tink tayer and
Network layer. These deats wtth etedri.at specit5cdtions, physicat
(oTecflon, transooa umtn9 d4d ?.,abrtrty,
U.r suppon HyeEr
The user support taye6 are: Sss,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 rogtctddE$tng,
. Rou ng.
1o.wh.t ac data 6..ms?
ln datagram apprcach, each packet ts treated indepnden y fbm
a loth.rs. 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 tlkes..re in rhe detivery of dara
from one apptiGtion proqrm on one devi@ to an app[caton posrad

Prcparcd By: ME, S, Artheeswart aplrr, r4Ec


lilr. P, Saravanan Ap/n. I4EC
/' -
IT 235T / NETWORX PRO@A}IMIXG AI{D TIANAGEMENT UNIT.1

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 dltis of tne tranEport taycr?
The serutces providd 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.yr 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 Eti.bt. 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 s.gm.nt?
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 tayerfme 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 sevEl.an flt togerhr tnto a singte daragram or t6me, the t.ansport
proto@l combines them tnto a stngle data untt, The ombi.ing pMes is
called concatehation.
lg.What ar th. rypei of hlttiptextng?
The types of multiplexing arer

Prcp.red ay: Mrs. s. Artheeswari AP/IT,lrlEc


I4i P. saGvanan AP/IT, MEC
IT 2351l NETWORK PROGRAMMING ANO II4AI{AGEI4ENT

t upward muttiptex,ng
. Oownward nutiplexlng
2o.What are the two possible tr.n.porr serul.es?
Two basE ryp.sofnanspod seruices are,
o Coniection serui.e
o connectionle$ seNies
,l.lhe tran.port layr .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 genric
behavior, uses gene c sumxs.
! Courtry domalnr Uss two characteE to identify a @untry as the last
suffix.
.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 onentd. Here user uses the @nnst;n
and then relea* the .onnectlon. Typl@lly one slde mak6 a propal
otherside @n aceDt lt. LcrleleDhone systems.
In cohnecnonls each mGsage crls the tull destinauon addB
and each one ls Euted thbugh the system independnt of all oties, The
fi6tonesend wlll bethe flEtone toairive. Eg:Postal system.
26. State fw adv:.tage. of IPvs over IPv4.

s. Artheeswarr AP/IT, MEC


P.saEvanan aPlrr, tlEc
IT 2351 / ENVORX PRO@AIIIIIiIG AND I,IAXAGEMEI{I UNII 1

r t ilrsadd'B spae
. Beilr h..d.. f6mar
. Xd optioc
. A!l@n@ for dtension.
. Support for r6our.e allocation.
. Support for more securily.
27, Explain about connedton terhinarion.
Fouractionsare needed tc close the.onnections tn both d rections:
. Host A sends a segment anrou.ci.g its wlsh for .onnection
establlshhent.
r Hosr s sends a segmenr acJ<nowtedging the reqlest ofA, After this
the .onnection rs closed ii one dire.rion bLt not n ih. oth.r
dlrecton,
. when Host B has finished sendins its own data, it sends a segment
to indtere thar twantsto ctose the connecuon.
i Host A acknowtedses the requesr of B.
24. wh.t .6 th. TcP op.r.Uo..?
r Encap.ulationandDe,capsutation
r Budedag
. l,4ultiplexrngandDe-multtpJexlng
. PushinS DEra
. ursent Data
29. Wh.a l. .ph6m.ral Portnqmbr?
A cltent pEqram running on th to@t @mputer deftnG ttsetf wtd1 a
port number, choen Endomly by the TcP eftwa running on the toct hosr,
Tils is @lled EphemeEl port number.
30. wh.t i. so.ket .ddress?
The cohbination ofan Ip addrcss and a porr number ts clted
socket Addres.
31. What .rc .lement needed for conmonicauons?
. tocat host
! Loet client proSEm

. Remote seder prosram.


32. Wh.t ls So.kt lnterface?
socket intefsc rs a set ofdectararions, definirions and
pbcedures tor wntrng clientseNer prog6hs.
33. Give son common APL that .upDorts to writ. .tienFsruer

Prcpared By I l4rs, S. Artheesrart AplIT, t4EC


I4r, P. SaEvanEn AP/r, iYEC
IT 2351 / NETWORK PROGMMMING AND I,IANA6E}4ENI I'GT.r =

programs?
Sone common APIS that slpports ro wrire ctient-seryer proqGms arc
,, Socker tnierf..e
t Transporr ayer Inter'ae
:1 stream Interfac
+ Thread rnreridce
+ Remote PEedureGtt
34, Spe.ify the Internet add,l$ .t uctlrc?
An IPV4 addBs is dehned as a sttu.tu.e G ed i. addr,
which ontains onty one fietd cled s addr if rype in addr r. The
stru.ture holdsan rP addrB as a 32 bitbinary number,
stru.t t._.ddr
t
in_.ddr_t s_.ddt

35. What ar the th@ $cket tl'D d.trn.d by s.kt interfae?


Th scket inte.fae dG6G the typer of s@ket!, They arc
steam ecket, the datagEm sodet aid dE 6w edet,
> StEam $.k t atto$ p'oe<a to ommuni@re using
fCPlP.rCP !s a patr of skts to @nnet one app[@tion
prc96m to nnotier acc ihe Intemet.
> Daa.gr.h ek tdtMpEs ro@mmunrGte using Uop,UDp
uses a pair of dltag6m skets to send a mesge frcm
appll@tion prcgEm to another a.ro$ the rnremet.
> It w.Gk tr p@vtde a..es to IcMp or ospF rhar dlre.uy lse the

35. Whrt i.littlecndli. byt. order?


A cohputer system that us$ lttue endlan ststeo stores the lest
signifcnt byte of data in the starttnq address ofrhedata !nir.

L-

37. What i3 Biq-Ehdl.r byte order?


A @hputer system that uses btg,ndLan system stocs the most
signifiant byte of data in the starflng addre$ of the data unit.

Prcparcd By: 116. 5. Artheeswan AplrT, MEC


I.4i P. SaEvanan APIIT, MEC
IT 2351 / IIETW(XX PROGRAMMTNG AND MAI{AGEMENT

34, whatarethe Byte iranipularion f(n.tiohs? 8ow they a.

The most common byte han putation fundtons are memset,


memcpyl memcmp.
Oeclaratlon for byte manipulatton fui.tions:
vold *m.hst (vold *d.st, int.hrr size_r ten);
void *m.m.py (vold +sr.,.ize_t len);
'desi.onsr vold
int mem.mp (const void *firs& .onrt votd *secon.t, stze_t ten),
39. Expl.ln th. so.kt tun.tlon?
The socket tunction is u*d by a pro@$ to create a socket. It
lakesthEe intger arguments and retum an integerres! !.
Int e.kt(lnt l.nll, int typ., int p6to.ot)i
-dennes lhe prctocol grcup
-defnes the type of socket
-set to zeb forTcP.nd UDP-
Thls tundlon etums a socket decdptor, whtch untquely defines
the @ated socket if the cratlon rs su.cesful. It retums -1 iI ther is an
emr, The socket descrlptor ls used by other tunctions to refer to the

40. Expl.ln the bhd fun.tlon?


Tte bind functlon blndsa socket lo a ocal socketaddrss by addrnc the
lo@l socket address to an aleady created socket,
lnt blnd(int so.rddr con.t sock:ddrcs. *toc.taddrr sockten-t
loc.r.ddrlen);
$ckfd is the socket descripror. tocataddr is the pointer to the
socket address of the local machine and localaddnen is th. length of the
lool socket address. To u* thls fundion, the c enr f6t needs to catt the
sockettundion ln order to use the retur.ed value as the socket descriptof,
Thls lunctlon sets values for Uie local socket address. This function retums
an integeri 0lorsuess and -1 ifany etro..

PEp.red By I titts. S. Arrheeswart AP/IT, t4EC


f,lr, P. saEvanan AP/IT, I,4Ec
IT 2351/ NETWORK PROGRAMMING AIIO MANAGEMEiIT

41, How an .ctive @rn..tion to a remote pro.ess i6 e3tablBl ed?


The.onnect tundion is u*d bya process (usually a cl:enD io
esiablish an active @nnedlon to a emote piocss (normally a server)
lrt .onnect(ant .odrld, .onst stru.t so.k.ddress *serveraddr,
s6.kl.n tsruerad.lrletr);
sockfd rs uE ed(et dEnptor .*ryeraddr is the pornter to the
remot soc*t add,s ;and *tueGddrren is the length ofthe 106ls..ket
address, To use this tun.tion, tne dienifiEt needs to cail the ecket fundion
ln order to use the rctumed EIE 6 th sod(et de*npior. lhis tu.ction sets
values for the remote setet add6. Inas tundion rctums an ihteqer, 0 for
suc@s and -1 rf ani eer.
42. Expl.ln d!. ll.t.n tunctid?
only the TcP e er 6lls tfie lirnen tuncuon. lt cEat6 a passive scket
from an un@nnecled $<lL BelbrE @lling t'te listen tunctron, the socket
mlst akeady be @atEd and rrE liEl addls 6elds set. This tunctron lnforms
the opehtlrg system tnat tne ffi is @dy to acept @nnedion thEugh

lnrllrt.nont sockLr ht b..dog);


socldd ls the soctet degidor .ba.!dog is tn .lmber of Equets
that en be queled for this 6nne.td. ,his tunctim rcurms an hteger, 0 for
suee$ and :1 lf any eror.
41. Expl.l. Or. .e.pt luncdon?
The acept tundron rs @lled by a TcP *d.r t moE the fiEt
Connectlon requet frofr thE cocpondlng quse. Ifthee arc no Equ6ts
dP a(ept tunctJon E put to sleep.
lnt.@pt(lnt sockld. .tru.t .o.k.d d rcE :cli.nLddr, .o.ll.n_t
.llert:ddrl6n)l
Thls function create 6 new socket (child ectet)that @n be u*d by a child
*ruerto connecttothe cllent. all the information needed fora new $cket is
omvided by tr ope-ctng syctem. fte return value
's
the new eLket
des.rlptor.
rt4, Expl.ln .endto systGm c.ll?
A @n.*tlonless prc.ess (pro@$ usinq UOP) i*us thesendto system
cll to send data to a po@$,
slte,t s.ndto(int .o.kr4 6nrt vold *id, .Ee_t bufl.', lnt flags,
@nrt struct sockaddi6. *toaddr, sockletr_troaddrt.r);
so.kd is the socket dGcnptor, buf rs the po,nter to rhe butrer holdhg tie
me$age to be 5ent, buflen defin6 the lengrh of rhe buffer, E.d the llags flelds

PEpaEd By : M6. 5. Artheesari ApllT, MEC Page I


Mr. P. SaEvanan AP/IT, MEC
IT 2351 / IETIyORX PROGRAIIIIIIIIG AND MNAGEMENT

5De.if6 out-of-band data or took ahead mssages, Nomaly it is ser to zeb.


Toaddr isthe pointerto the socker address ofrhe receiver, a.d toaddrten isthe
length of tle seket addre$. The tunction turns the number of .ha6.tets
se.ds iftherc rs nc eror and 0 otheeise.
45. Erplain r.cvfrcm .ysteh.. ?
Aconnectronte* pbces (process uslng UDp) issues rhe reryfrom system
6llto recelve from inmmlno queue, the datagEmssend by a remote prcess.

..ize_t recvfrom(lnt .ockfdr .onst votd :but, .tze_t bfftenr int flag3,
struct.ock.ddre6s.rrcmaddr, so.tde._t *r.on.ddrten).
socKd is rhe s@ker dscnptor, buf ls the potnter to the
butrer wher the mesge wJtt be stored, buflen defines rhe tength of rhe
butrer, and tn flaqs fields specifies out of band data or lodkahead
m6*ges. Nonally it rs *tto zero. Fromaddr ls rhe pointer to the socket
addre$ of tne *nder, and fromaddrten is ihe tenqth of the seker
addB. Thls tunction Etums the ouhber of chaEcteu send tfrhere ts no
emr and 0 othBt*.
46. Exphln rc.d 6ysrch @tt?
A connecnon{riented prcc6 (oD@s using TCP) isues rhe Ead
system cll to @lve datagdms from a Enore po.e$,
sria_t rc..t(lnt .o.krd. 6n.t votd *b!t, sir6_t bufl.n),
sockfd ls the socket descitptor, buf ts rhe potnrer to tie b!trer
wherc the dara wlll be srored and buflen deffnes the te.grh ol the buffei
Thls tunctlon Eturns tie numbcr of bltes ecetved tf su@$fut,O lt end-
or-file @ndltron ls derecr.d,.nd -1tr rhere is a1errcr.
47. Explaln wrire .Ft.m ca[?
A con.ection oriented process (prccess ushg-rcP) tsslesrhewrlte
system callto send daraqramsto a Emote prc.ess,
$iz._t write(tnt .o.kfdr 6nst void *bofi size_r buften);
so.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.
This tunctton returns the number or bytes *nt(wrttten) tf su@s.tut ,and
-1 if there ls an erbr.
44. How . TCPconndio. terhirard?
t3
The do$ tunction ls used by a proe$ to close a $cket and termlnate a
TCPconne.tton.
nt ct os(int .ocktd )
i

The scket de5(iptor is not valid afterthis catl.-rhis tunctio. returns an

Prepard By: rvtre. s, Artheeswari AP/IT, MEc


!4r P, SaravEnan Ap/tT, I4EC
n8s1/ NErwoR'( pRoGM _!!I:L
E lnteger, 0 ior sleess and -1 tf any effor.
F 49. wh.t isa Dar.ntseruer?
Asetuer running infniretyand accepting conne.rions fr6m.tients is
catled a Darent seruer.
so. What rs iterativ. seruer?
If a client reqoest to a seNer for a esource, which in rurns gtves rh
iesource form other server ca ed itehriveseNei.
51, what is .on.urrent s.Be?
lf many .lrent a..e$ a seryer Gtted concurenr 5etue..

e Th ommunietion sttocture used for socket prografiming


(DEC 2O11/ 2012)
isc[ed
ecket. It is an end point of .ofrmunicarion to whrch a nafre .an be
bound. Two proce$es need a socket at each nd to communi.ate wtth
each other, The socket vatuesa
: Spe.lfy tne So.ket Ad d ress 6tru.r u re?
The applieuon prcq.am rhar use the TCplIp prcto.ot suire ned a
structure 6lled a socker addrss, which malnty hotds an rp addre$, The
structure has five fields,
, strucr sock.ddres.
I
ulnta-t .in-leni
e_trmlly_t .in_famlY,
lnJrort_t .trLrorq
.tructitr_addr .tn_addr;
.har .ln_z.ro[3t;

Famlly - defines the prorocot group


TyPe - defines the type of so.ket
Poto.ol - *r to zero lor TCp and UDp.
Local $cket address detins rhe leat ectet address, a structure
of rype sockadd ress,
- deflnes the remote socket addressl a
skucture of lype so.kaddress.
what do you me.n by so.ker abstracrion? (DEC 2OO7)
The socket is the baslc absrractlon for network.ommuni.ation in th

> Defines an endpolntofcommunicauon fo. a process

Prp5r.d ay: r!8. s, Artheeswan ap/tT, t4Ec


l4r, P, Saravanan AP/IT, MEc
IT 2351 / I{ETWONX PROGRAX IIIG AI{D IIAI{AGEMENT UNr.1

> Opedting systen malntains informarion about the socket:and its

> Appli6tio. eture.@s the $cket for seDds,


@. siall lo..l.hd rmote sockt addrc$es be
REXOTE AND fOCAf ADDRESS
> G.Bo.knam.:
Retum the locl protocot add@s asociatd wth a so.ker,
int getsockna m.(lnt so.kf4 stru.t.o.ka.rdr * to.ataddr,6o.kt.n_t
*addrten);

Return the remore add.6s asso.tated with a


ecker.
int g.tp.rn am.( i nt so.kfd, structso.kaddr *peeraddr,.ockten_t
*addrten);
Both the functions eturns O ifok else 1cn eror.
sS.What iEth. u.e of bind O syrt m ca[?
The bind tun.tton bindsaskettoa to@t$cker address by addlno the
$cket addls to an alr6dy c@ted $c,et,
bhd(lnt.ocldd,.oGt s.kaddE..to6taddr, s.kt.n_t
loc.l.ddn.n),
sockfd is the ecket descrtpror. loGladdr is the pointer to the
$cket addrss ofthe loclmachlne a.d lo@taddrlen ts rhe tength ofthe tocat
socket addr*, To use rhrs tuncnor, the clent nEt.eeds to cal the socket
funcuon in order to use the rerumed lalue as rhe socket d6criptor. Thts
function *ts values for the loctsockt addres- ftis tun.rion returns an
succs and -1lf any error,
lnteoer, 0 for
57. Expl.ln th. so.k t .tr{ctur h bneL
Socket Pograhming ro hotd informauon abouttheaddBss and port and
other Infomation, |4ost $cket tuncflons requirea pointerto a sockeraddress
strudu'e 3s an argunent.
^
(@!or"tmeui.r, tt*".n on rr.rauv. *Ner and.on.urrcnt seru.i

f. i,lany request are poces*d 1. One rquest is prcce$ed:ta

2. 1r rscalled when thenme When the timetaken to complete


talen to completed the the pro.ess ls,essthls seruer ls
equest ls infinite or long,

PEp.red By: Mrs, S. Artheeswan Aplrl, IyIEC


!rr, P, Sa6vanan Apln', NtEc
IT / NETX/ORK PROGMM
'351
3. The requesrcn be ofany
complexlty and duratton,
4. Setuer software husr be
proqEfrmed expltcttty to

t.t*u.n Tcp so.k ts ard Uopso.kers (fiAy 2orr)


"r<Toi"tinsui"lr "i
Rellable, Connection Oriented prolocot

Arlides suaranreed det.rery orTDoes nor provtde gudE, (eed de very


pacrets lofpa.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. r,ieans the packets thar ae sent paciet will reach in timetothe

@ eq
"*.

{
length of th structurc */
addres famrly : Af_ XXX value
prcto@l speclfi. address */
),

/fr x(
(v oorine wen-rnown pon. (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,s rransmission connot protocol (fqe) or
the User DatasGm prctocot (Uqe). porr numbets o to 1024 are reserued
for pnvlleged serures ahd designated a3 welt-known ports. thrs lst of

Pr.p.rcd By: i46. s. Arrheeswart Aplll tr4Ec PaEeTz


Mr, P. Saravanan APIIT, t{Ec
IT 235T / I|ETWORX PROGMA,II{II{G AND MANAGEI\4ENT UNIT.1

rell-known po4 numbe4 speL'fre< rhe oo.r used oy the <eaFr p.oce$ cs
its @.tact port.
-6 Ddttr. $d..r.nd .t out tr. typ5.
The @hmunlcatlon stru.lure used for socket programminq is caled
so.ket, It is an end pornr of communi.aflon to which a name .an be
bound, Two processes need a socket at ea.h e.d to communi.ate with
each other. The socketvatuesare Ipaddress and port number,
TYps of So.ket:
The so.ket interfa@ defines three types of sockers, They are
stream socket, the datagram socketand rhe Ewsocket,
> Stre.n socket altows processes to communtcate using Tcp/tp. TCp
uses a palr of so.kets to connecr one appticrion prcqram to another
acoss the ln rernet.
> oatagEm scketallows proces*s to.ommu.i@re using llDp. uDp
uses a pair of daragEm sockets ro snd a messaqe from
.ppliotlon pogrm to another across rh. rnr-'neL.
> Raw ro.tct provtde a@$ ro tcMp or OSPF that direcfly use iie
serutes of Ip,
63. Dl.tlnggi.h betw.en Tcp so.&6tr .nd UDD s6.keb. (MAY 2011)

r unreliable dellv!ry
r h-orde.gua6nted I no ordersuacntees
! no notion oftconnecfloni - app
lndl@tes dest. for e.ch packet
i can send orre@ive
r srrucrure is soc( DGRAM

64, Whlt l. meaDt by tDst byt ordertng?


r' HOST AYIE ORDER
. It is the byteorderlng used bya gtven system,
. Itcan be blg endi.norltttle endian.
+
Pr.par.d By ! Ivtts. s, A.theeswari aplrT, MEc Page 13
l4r. P. Saravanan AplII, MEC
rI2351/ NETWORK PROGRIMMING AND MANAGEIIENT UTrI.I

i PART - B
F
I 'kxetdtn tfi6 TcP lay.ring in details wirh neatsket.h.

> OVERVIEWOFTCP / IP PROTOCOLS

Web Clients and Servers.ommuni.ate ustn! the Tcp p@ro.ot_ TCp


@mmunicates with the dara |nk tayer lsrnq lp proto.ot. The actuaL ftow of
lnformation between the ctient and seryer goes down the prctocol srack on
one side across the nerworkand up the pbto.otsta.k on 6therside.

FROT

Figure | Clent and Se ercommlnicalon on the same Erhernet usinq TCp

fCP : TRINSI{ISSION CON'ROL PROTOCOL

lcP prcvids connectio, berween c[ents and seder. A Tcp ctient


st6blishes a connedion wtth the seryer, qchange dara wlth rhe seryer
and then temlnate the connection. TCp provtdes Uow co.tot, relabtl,ty/
tullduplex and al$sequen@s the data b, associating a sequenc number
wlth evry by,te that tt sends, TCP conratns atgorithms to esimate the
round t.lp Uhe (RTT) bebveen a ctienr and seruer dynamiGtty, so that tr

PreDired By: i4rs. S. Artheeswarl AP/IT, MEC


i4r. P, SaEvanan Aplrr, MEC
IT235I / NENVOR( PROGMMi4ING ANO MANAGEII4ENT UNTT.I

knows how long to weit foran acknowteloemenr. TCp always specjfies rhe
no. of bytes to be*nr bythe peer. This is called advnsed winlow,

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

Prcpaied By: I4B. S, Artheeswari Ap/rr, MEC


l'1r. P, Saravanan AP/IT, 14EC
IT 2351/ NEaWORK PROGRAI.4MING ANO IIANAGEMENT

The Transport laye r facilitates two rypes ofcommunicauon:


! conn..tion-oriented ocP) - A connectron must be established at the
Transport layerofboth systems befoE the applicatioi.an transmltanv data
. conn..dorl6s (uDP) - all systems do not need to etabllstr a @nnedion
with the rcipient pnor to data exchaige. TCP is a more Eliable foro ordata
exchanqe than UDP,
N UEIu9Bf,-LAIEE
Ihe NetNUk lnt4lace /ays (al$ 6lled the Network ,(C6 laver) is
responslble foi pladng TCP/IP pa.kets on the network medium and @iving
TCP/IP packets otr the netuork medium. TCPltP was designed to be independent
of the network a@ess metnod, frame format, and oedlum. In this wav, TCP/P
can be used to conne.t ditrerins ntwork types. TnE layer include IAN
technoroqies su.h as Ethernd end Token Rlng and wAN technoloqi .uch .s
X.25 and FEme Relav, Independene ftlm any spe.lfic network technologv glves
rcPlIP the ablltty to be adapted to new technoloqies slch as Asynchrcnous
TrEnsfer ode (ATM).
O DAIAUI{ !4XEA
It of comblnation of datalink and physlcl layers that dals wlth pure
@nsists
hardwa (wlrs, stelllte links, I!eb4o4-]l!e@!e--ral!5, etc.) and a.@$
methods such as csi4A/cD (6rler *nsed multlple ace$ wlth @lllslon

2. ExDl.ln the aollowlng sy.t m ellr in d.t ils


. CONNECTO
. BINDO
. LISTENO
. accEPT0
> r!!Elg9!!EgEt94!!i
The @nnect tunctlon b used by a TCP client to Btabllsh a @nnectlon with a TeP

,lln.lud.<Ey!/Eocket.h>
int conn.ct(l.t ecldd,.onst 3trsct .eh.ddr .sMdd., sckle.-t

o sockfd-> ecket descrlptor value,


o seNaddF pointer to socket addres structure . the socket addEs
structu@ must contalnthe lPeddre$ and po.t numberofthe server.

PrcpaEd ay r Mc. S. Artheeswari AP/II, MEC Page 16


I,4i P. Saravanan AP/IT, l4EC
II 2351 / NETWOnX PROGRAII'.{ING AND MANACEMEM

o ddnen-> iJengrh

Notava d socket descrlptor


EIIOTSOCK If the fiBt argument ls notspecified,
EISCONN r the so.ket is.lready @noected.
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 . irternet protocot
addre$ is a comblnation ofeither 32 bit IF4/4.ddress or 123 bits tpv6 addBs atong
with a 16 brts TCP or UDp port number
lnt blnd(int .ockt t, .or.r 3truct s.kaddr *my!ddr, so.tden t .ddrter)i
. ,t returns 0 if OK & -1 on errcr
r so.kfd- sockct d6cnption
r !1y addr -the address ofa sttucture rhat spectfles an ip address.nd port number.
. Addrlen- The size oftne.ddr6r rtruc1ure r. bytes.
EcS!!-Eo!lg
Retum 0 tf sucstul &,1on ermr.

Not a valld socket dscriptor


ffthe nrst argument rs not specified.
Ifthe address is akeady bound to it,
If the ocal address argumert polnter

Kernel.hooses IP address and port

Kernelchooses IPeddre$ and pbess specifies port


Prccess speclRes lP address, temelchooses port

Prcpared By: Mrs, S. Artheeswari Aplrt, i4EC


t1r. p. saravaran aP/Ii, t4Ec
IT 2351 / NETWORK PROGRA'.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.
1, The llsten tundlon @nverts an unohnected ecket rnto a passiv socket
lndloung tiat the kemei should a@pt ihe rncoming conneciion request dlreded

z. It spectRe ttre muinr. nuhber of @nEuon the *emel sh@ld queue ior thls

alnctodc <Eysl.o.t r.h>


ht ltd.tr (int $.ldd, ltrt !r.kros);
r rr rerum o,rox, -r on em' tv o
-s7*
The kemel mahtaiG two q@u6:

It @ntahs a. ent y ior each sYN that afilved fom a clrent for whrch the se er
ls awalting @mpletion of the three way handshake.
2. Completd connedlon oueue:
ft@ntains an ent y for eadr cllentwlt1 the Tcp three way handshake has

s@kfd- socket dscrlptor


Backlog- 5lE of h@mhg @nnectloo request-

Not a valld socket de*rlptor


r tne fiBt Ergufrent is not speclfied,

The accept is @lled by the TcP server to retum lh ndt completed onnectlon
trom the front of the .ompletd conn.tion quue, Accept .at6 a new socket and
Eturn the descrrptor of the nesectet to the.aller. The seruercan transfer dsta on
rhe new sdket afrer finlshlng ihe se er .los rt.
*lnclud. <3y./.ock t,h>
lnt .@pt (l.t sockfd, .lnct soct rldr *.la.ddr, .o.kln-t .ddilen),
+ Non neqative dscriptor it Ok
t Else"l on errcr
sockfd-> ecket des.rlptor
Clraddr> client IP addc*

Prepared sv: ME. S. Adnwan AP/ff, MEC Page 18


Mr, P, SaEvanan APIIT, i4EC
Il 2351 / NEIWORK PROGRAMI.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. This is s@portd only in stEm.

Nol a valld so.ket d es.rlplo r


ENOT,SOCK If ihe fiBt argument is notspecifld.
socket is not a socKET sIREAI.4.

@ yp,**",rn o"*en th irer.tiv. sew.r rnd

> lIEiAflVE SENVER:

A seruer is a pro.ess whi.n offe6 services. A setuer w5its for rads and
pEcesse a clients requet aor a se *.

Seruer @n be dasified b6ed on following


1. (6nn*don 16 d 6nnecfrmqtsta'd).
Thelr @mmunl@tlon net}|od
2. The hfomauon tlEy mahtatn{state t6 d st te tull);
3. B.sd on rheir eNie(iteEtive or @ndrent).
a cotrn..don orlsld smE:
. Us TCP for mnnectlon onefted mmhunl@tbn
. Prcvlde rcllable tEnsport
t SNeEarcsimpler
t U* a *parate socket for each connectlon,
> clDDCggOEleS!-EltllEi
t Us UDP for conne.tionlss communi@non
. Does notguadntee Eliable transport
t The se erand cllent are 6mpll.atlve.

Does not maintaioany iniormatlon Eboutthe outqoing intedctlon wlth

Requires long me$ages.


Allinformatbn aboltthe request must be pla@d ln allmesges

Prcpared By I Mts, s. artheeswari aPln, MEc


Ir4r. P, Saravanan AP/r, MEC
n r35r i NFrWORT PFOCRA ,-"-,
> Statefut serven
t Maintains information about the status ofthe ongoing tntormauonrith the

r l4aintains few infoimarion between request.


. Requires sharler n'essa9es.
. Is unretiabte ota connedio. terminates abnorma[y.

Iterativ. or seauenttar s.pefr


' An lteErive setuer*tus singte.tientar a time.
t Handlesone requestara uhe,
. client waits for alt pvrous Equests to be pocsd.
. It rs easierto design an,l imptemen!.
! It is surtable when the *ryt@ time for each requst is sma[.
r It lssuitable for empte sefrrer sro as nME se rc.
. Iris notsuitabte when rhe seNce flme.

INIERNET

r The li6t dientrequest to set a fiie of size 2oo r,4bytes,


. The se@nd client Equesrs to qera fite of20 bytes between the 2nd ctinr
has to wair untii the procssing ofctient ends_
> CO CURNEiT' SERVER

t A $ruer cn handte huttipte .tienrs ar the sme Ume in paraflet, and this rype of
a s.Net ls @lle,J a fuhcurreht setueL

Concurrent Vs ft.Etiv. reruer

i4anv eauestare Drocesed ata I


one reqJesr r po(eesed dr a Lme

Prcpard By I r4E. s. Artheeswad AplIT/ MEC


,,4., P. saGvanan AplrT, MEC
IT 235I / IiIFTWORX PROGRAIT'MINC ANO II4ANACI I'ENT

When the trmetaken to comptete rhe


process is less thisserverls used.

fte
equest cn be of any
@mplerity and duraiion.
Server software olst be
programmed explicity to handte seryeris locked whlle dealinq with a

Dl..urs the synta.ticat isue. orvarious addre.s 6nve


^@ , coitvERsro FuNcrrotrs:
(ilaY
@. appREss
There are two or.uDs ofaddress conveEion functio^s:
'004)
L net aton, net addr& inet_ntoa : convelcs btween Ascll strrnq and
network byre ordered bin.ry vatues. appticabteonty for rpv4Address
2. inelpton & rnet_ntop : convets presentauon to numeric &numencto
presentation, Applrcable for both IpV4 & tF4/6 address.
/ Convcrclon berween ASCTI sHn$ & n.rwork byte or.ter:

t include <arpa/inet,h>
int iret aton(@Gr char* strptr, stru.t tn_addr .add rptr);
> Retums 1, if strinq was vaid,

o Th tunctlon rnLaton @nverts the d,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,

It returnsthe 32-bit btnary network byte oder vat! & INADDR-NONE it

ln_addr_t rneladd(consrchar*skptr),
> Returns 32 bit bi.ary nework by,te ordered rpv4 Addre$,
INADDR NONE ifan eror.

It.onverts 32 bits binary netwo.k byre orderd rPV4 address tnro rr5
corespondingdotteddecimal s$ng&rerurn poinrertodotred d*imal

Prep.red By: Mc, s, A.theeswari aplra, MEc ?aAE2i


i4r. P. saravanan APIIT, r,4EC
rI 2351/ NEIWORK PROGMI.4

/ Conv.r.lon betw.en presentation and numert.:


These are lsed for both IPV4 & IPV6 addre$,
P-> PresenraUon - ASCtl srring
n > nunii. - binaryvalue

int Inet_pton(int rdmily, 6n5t char.strptr, void.addrptr),

0 if not a valld p@nhtion fomat,

. Family - AF_INET ilPv4l


aF_rNEr5 UA/61
. lfthe famrly is not supportd it rrurn the errcr -1set ro E
. The dotGd decimal shin! stored ln shptr is conve.ted and st6ed thbugh

It converts rbm numedc (add.ptr) to preenrarion (strprr),

const.har *iret ntoD(lnt familY, const void *addrptr,

- Retuh pornterto resllt


len -> sla of the destrnatron to pevent the tun.d6n from
deridl.q the 6uers buffer.
IPV4 . 16 bit . I'{ET_ADDR5TRPIR
IPV5. hN, II{ETSJDDRSTRPTR
'5helntop is it EqurB the cller to pass a polnter to a binary
The preblem riBl
addjB. The addr is nolmlly ontarnedin a e.ket addr structure requrring the@ller
to know the lomet of $e structurc and addlls fdmily. To solve this we use

G.n.6l R.pEed.tion
32-bit binary lPv4 address

mapped or lPv4 compatlble


IPv6 Address or IPv6 Address

Prcpared By: MB. S- Arthee an APltT, IyIEC


lrir. P. saravanan AP/II, I4EC
rI 2351 / IIETWORK PROGMXMING AND i{ATAGEI.,IEI{I UNII,1

@n't" ""te on uvt oracrins run.rons, (l,lAY 2OOa / DEC 2012)


i) BY'E ORDERING FUNCNONS
The btt6.an be srored l. memory tn two weys
1. Utite End an Byte orde.inq
2, Big Endian Byte Ordedxg
r' LITTLE ENDIAN BYIE ORDERIXGI
LSB nr Low ord.. byLes as Lhe rra r -q dda.esl

hcreasinq Memorv Address

10.23.14.6n be represented in
LSA
00001010 00010111 00001110

00001010 00010111 00001110


a+3

DEC VAX Compute6 Intel lllcbpb.e$o6

BIG EI{DIAI{ EYIE ORDERINGI


High order bytesorMSBas the starti.g address,
lncreas nq Memory Addrrs

HIGH ORDER BYIE

Prepared BV: r4B. s. Artheeswari AP/fi, MEc


rllr. p. saravanan Ap,/Ir/ MEC
IT 2351 / NEIWORK PROGRAi4I'1ING AND IIiANAGEMEIiT

10.23.14,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, char**argv)

harclsizeo(shon)1,
) un;
un,s=0*0102; alol : c)'
pnntr C%s", CPU-VENDoLOS); c('::ol
r (sl@(sholt)-=2) -
{ WW\.,,
r (un.40l==1 && un..I1l- =2) c'-')'".
Dnn60brs endran");
el*lr (un.ciol==2 && un.ctll==1)

7 TYPES OF BYTE ORDEN BASD ON BYIE ORDERTI'IG FUNCIIONS


/ iIETWOR-X BYIE ORDER
. Networkl.g prctocols @n choo$ thek own blte otder
. TCPI1P has the big endlan system.
/ HOST BYTE ORDER
. ft is tle bt4e orderins used by a given system.
! It@n be blg endlan orlittleendirn,

Pr.par6d By I i4E. S. Arthe$ari APIIT, MEC P1ge24


Mr, P. SaEvanan APIIT, i4EC
IT 2351/ I'IETWORK PROGRANiIING AND fiANAGEMEITT UNIT.1

/ AYTE COI{T'ERSION FUI'ICTIONS:


. Frcn nost to byte or.ter
^etwork
. htons - host to netwo* shortU6 btt tnrl
t htonl host to network tong t32 bt ntl

ulnt16_t hrons(uint16_thostl6bitvatue);
!int32 t htonl(uint32 t ho.t32bttvalue)i
returns value in networ& byle order

.etwork to host short [16


network to host lonq 132

ntoh(uint32 t #32bitvarue),
- retoms value in h6t byte o.dr

. +----!-
I r6bir | | 3i bi, I

6. E pl.ln th. Typ6 ol serures?


. Conn*tlon Odented seruicG
r Connectlonle$se ices
> aonn.ction orleht.d and conne.rlontcs.rervtces
o In connsuon orlented method sston t5 created betore transmittinE
dat6. It pbvrd$ a rellable data stream a5 tt ensures the sequenual
transmi*ion ofdat:,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.Uon device before data can
b sent and hence a vidual li.k ls establrshed between sender and
reeiver, This process is alled handshakina,

Prep.red By: ItlB. S. Artheeswari Ap/rt r.4Ec


Mr, P,sarava.an APIIT, t4EC
rT 2351/ NE.rWORK PROGMi4I'1ING AND I\4ANAGEI,IENT UNTT.I

o After that data is transfercd sequentiaty by proces:.ng


actnowledgements. Stiding window and Stop and wait are lsed to
trovide flow contro and Cyctic Redundancy Che.ks ae usd to provide
etror detecrion_ Th6e hethods c.n eirher be imDlemenred rn the data
lrnk raver or rn the transport t:yer, Tcp provides a onnedioi,oriented

o In connectio.less kansmision thre is no need to estabtish


connectlon. The sender lust starts transmttunq data thats why it
6n.ot provide the same reliabllity as offered by @nnetion{nented
nethod, These technrqu$ are lsed ln the lrol!|cff! netwo*s, rn
thse networks there ts need of maintahtnq the state information for
the sender and Eeiver devtes rhar,s why ir can onty ofier a smalt
number of se ices. However the speed or cofnectionle$ letsrqLE is
better than tho* of connedion,ortented ones beouse they do nor
prcvide tow contrcl and errcr deredion. u9P provids .onneclonte$

In onnectloo oriented communlGtion oneu* qulded m.dlnm. Bur ln


@nnectlonls romfrunictlon there's no need ofa.abte, tt atso
naned as wrcle$ @mmunloton,

rffin

S. Artheeswari AP/rl, MEC PaEe 26


P, Saravanan APIIT, i4Ea
IT 2351 / I'IETIXORX PROGRAI'IMIIIG ANO MANACEI'4ENT

7. cralii. .bout $cket, 6nnG.t, bind, listen :nd aeept lun.tion. (DEc 2012)

> E9!!EMqEQXi
The tun.tion is.alled to create a socket to perform client seNer applictlo..
+in.lude<sys/sotket,h>
int socket(lnt famllv. int type,lnt prctocol);
t Retlrns non necative desc.iptor if OK.

, Family - specifies the protocol family.


1. AF INE PV4 Protoco
2. AF INEI6-IFV6 prctoco
. Type - specitls ttre sockettype.
1- stream Socket (socK SIREAI'4)

2, Dataoram Socket (socK DGMl.l)

3. Raw Socket (SOCK-RAW) used for both TCP & UDP

Pemlsbn io @ate ecket ls denied


The s'stem has no available buffe. space

> rrE-t9llEcrcAlE
aTcPclientto establish a @nnction wlth
The connect tunctlo. ls used by a TcP
*irclud6<sys/socket.h>
lrt @nnct(int so.tddr@rst struct so.haddr *s.dtddr, socklen-t

r sockfd-> socket descrlotor value,


. servaddr polntertosocketaddress svucture, the socket addr$
stBctu must contaln thelPaddress anc port number of the

. Addren-> Lensth ofhte se er address.

Pre?ared By: I.4rs- s. Artheeswari AP/IT, ltlEc


r"l r. P, Sariva.zn APIIT,14Ec
IT2351/ NETWORK PROGMM

*
F
Not a valid socket descriptor
If the firet ar9umentrs notspe.ified.
lfthe socket is alr,aady conn.ted.
ETIi4EDOUT lf ihe mnne.tbn rs notestablished
Ifthe polt number specified is not waiung

> BINO FUNC.IIONi


The bind tun.tion assigrs . local pmto.ol addr.ss io a socket. 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.lddr @nsi stru.t.o.k.ddr *myaddr,.ockln t.d.ld.n);
o It returns 0lfoK&-10. etror
- o Sockfd- socket des.rtption
o Myaddr -the address ofa structure that specifies an ip address and port

o addrln- The srze ofthe address structure in byts.

Retum 0 if su@stul & 1 on errcr.

v.lu.lr mo lc,!* orth..mr


GBADF not a varid so<Ier dsnpbr
I
ENoTsocK I r the first arqument is not specified,
EADDRINUSE llrtxe add6 is already bound to it.
EFAUTT I rthe lo@laddEs aEument pointer is invalld.

(ernel.hoors lP address and port


rernelchooses IP address dnd pm.es specrns port

Proess specifies IP address, kernelchooses port

Prcp.red By I i46, S. Arrheeswari APlll, MEC Page 28


1,1r, P, Saravanan APllT, MEC
IT 2351 / l{ETWORX PROGRAIIMING AilD IIANAGET,iENT

Proes specines the Ip address & port

> tHE IISTEN CAL[:


Itis called only 6y a TCPsetuerand t pedorms two functioni.
a. The listen fun.uon converts an unconne.red sockt tnto a passtue socket
indiGtrng that the kernetsholtd accept the tncoming connecrion request
direcred ro this socket.
b, It specrfies the maximum numbr of conne.tior the kernetshoutd queue

#in.tude <.y./sock.r.h>
ht listen (lnr.o.tt4 i,tba.ktos);
t It eturn 0 ifoK, -1on eror.
The ke.nel malntains two q!eu6:

It @ntaiE an envy for ech s.rN th.t arived arofr a client for which rhe
erer rs aMiring @mplerion of tne tnE My handsh.ke.
2. Codolr.d dne.ri6n outu.:
It dEi6 4 6Ey for ech drent wiur dE TcP dle Ey handshake ha
@molt d.
s6*ff- $det deiptd
A..klog- stse of lli@mt,lg mnedion rEqueL

Not a lid sockt denptor


ENOTSOCK lf the flBt argument is not speified.
> rHE AccEPT FU CTIO !
The accept ls .alled by the TCP seNer to return the next completed conne.tton
fbm the frcnt ofthe completed cofnect on queue. Ac.epr creates a new s4ker and
Eturn the descriptor of the new socker to rhe @ller. The sefrer can nansfer data on
the new socket after fintshing the *ruer ctoses tt.
*includ6 <sysl.ocker',h>
lntE...pt (lnt so.tfd,.truct sock ddi *.lladdr, socktetr taddrten)i
t Non negatTve decriptor ifok

So.kfd-> socket desdlDtor


ClladdF> clientlPaddres
Addrlen-> ength ofthe sec.nd argumeit.

Preparcd ly r M6, s, Artheeswarr APlrr, MEc


Ivlr, P, Saravanan aP/r'I. MEC
.T 2351 / IIETWORK PROGRAMMING AND i4ANAGEMENI UIIT.I

The connected socket is closed ach time wt.le the tisteninq socket
remai.sopen for the life ofthe se&er, This js suppc.ted onty i sneam.

Not a va d socketdescrpio.
If the nrstargument is not specified.
socket rs not a socKET STREAM.

yErphin the v.riou. so.&ettunctions requtred slngle..Per


Eg!!{t. Expl.in with the hrp of a frow chart
luncilons m:y b used.

5, Read

IISTEN(
socKET( )

crasE( )

READO

crosEo

PrcpaEd ay: Mrs. s- Artheeswan aP/IT, tlEc


i4r. P. Saravanan APIIT, l4EC
rT 2351 / I'IEfWORX PROGRAMMING AND MANAGEMEI,IT

> SoGIELEU!.SI!9!!
'I1le tunction is@l,ed to crate a socket to perform client *ryer appll.atlor,

*ln.lu.le<sys/so.ket.h>
int so.ket(int family, int typr intproto.ol),
. Returns non.eqative dscnotor lfoK,

. Family - specifies the protocolfamily.


1. AF INET TPV4 prcto.ol
2. AFJNET6-IPV6 protocol
' Typ - specifis the socket type.
l-Stream Socket (5OCK_STREAI4) - Used for TCP Connedion
2.Datagram Socket (SOCK DGMI,4) Used forUDPConnetlon
3.Raw Socket (sOCK_R^W) - U*d for both TCP& UDP &ICMP.
r Potocol- set to 0.

Peml$ion to @ate s4let I5 denid.


The system has noavaitable bufrerspate.

The blnd tun tion l@l pbtocol address to a socket , intem.t pbtocol
6slqE a
addlE ls. Gmbhanon of elther 32 bit Iw4 addEs or 124 bts lPv6 addres.lonq
wrth d 16 blts TcP or UDP port number
I blnd(l $ctdd, 6tr.t st.u.t so.kaddr .my.ddr, .o.UrLt .ddrl.n),

. sockad- socket descrlptlon


o My addr -the address ofa structure that speciflB En lp address aod 9on
numb..
o Addrlen- The size ofthe address structure in bytes.
aclc4rsds
Return O if su(estul &-1on etror.

Prcp.red By ! t{6, 5. Artnesw.rr aPlr, MEc


Mr, P. Sa6vanan APlrT, MEC
Ir Z:ST I NEN,^/ORK PROGMM

ERRON CODE

Not a valid solketdecriptor


rr e fiBt arsu;entIs notspcifled.
ffthe address l5 akeady bound to it.
rfthe lc.al addBs arsument pointer

NESUIT

Kernel choAs6 IP address and Port


(enrerchooses,Paddress and proes epectrrE pon

Prccess specifis IPaddEss, kemelchoose po't

Pro@s specifies the IP addEs & port

> THE LIS.IEII CALL:


It ls 6lled only by a TcP saruer a.d lt prfoms two tu.ctions'
1. The t6ten tunctlon onverts an un@nne.tEd $cker into a
pa$lc scket
I.dbrjng that UE kernel should a@Pt the lncominq connection requ6t
dlEtld to tnk sket.
It spedfie tne mdlmum nlmber of .onnection the kemel should
quae for
2.
this ec*et.
tlnclud. <5r./.o.,GLh>
lnt lltar (lnt 3drdd, lnt b.cldr,g);
t It erum o Ifox, _1d em
Tie kernel malntains tm queu6:
3, In.ompleb onnedion du4e:
ft @ntaiE an entry for 6dr sYN that anived from a cllent for whlch the
se.Jer is a{6ldng ompletlon of the th@ @v h'ndshak'
4. caodelrd @on!cl9!-sul1rei
It contahs an ntrv for dci clle.t witn the TcP thEe sav handshake h's
completed .
sdkfd- socket dEcndor
Bacldog_ slze ofln@mlng connectlon request

4
!*;iia ay, v^ s a,tn".swa,r aPlrr, MEc .Pase32
I.4r. P. saravanor APl'T 14Ec
MTNG AI{D MAIVAGIT4EN T U TT.1

Not a valid ecket descrlptor


lfthe firet aroument rs not specifled.

IEE4CeEerEUtggell
The accept iscalled by the TcP sere. to return the nertcompleted connedion
from th front of the omplted connection quele. Aaept crates a new socket ard
retlm the de*rlptor of the new $.ket to the @ller. The seruer can kansfer data on
the neh socker af,er finEhing the rede' rlotss lr,
*includc <.v./.o.kt.h>
t a.ept (irt s.kfd, strct so.k.ddr +.lladdr, socklen-t rddrl.n);
t Non neqative des.rrptor if oK

satfd-> *ket d6olptor


dladdr-> dlent lP addlE
Addrten-> lsEth of rne snd
The d,E t d $det rs ded 6dr tifttn etne listenlngs@ket
EmiE ocar lh. uE liE ot t E *ruer. Thrs E $p9dted only in steam

ilot . v.lld sd@t d6olptor


EI{OTsOC|< r tne tct aqument is not sp'hed.
saket is not a soc(EI-sTRE ll.

eloslEuqroli
it is used to d6e the scket and terminate a TCJ connedlon
*h.lude<uni.td.h>
int.los(int so.&efd),
. It return 0 ifOK
. -1on eror.
Else
. tt marks the $cket as closed and return to the
. The socket decriDtor ls no lonqer usable bv ihe
used as an argument to read orwdte.
. 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.e

PEDared ay r M6. s, Artheswari AP/Ir, MEC Page33


I'4i P. Saravanan APln, MEC
viriols scket lrnctiors requlEd to lmplement
9. Expt.in thc
modole. Expl.l. with th. h'rp of a flow ch:rt tn' scqun'
functloG m.Y b. ut.d.
The tunctlon calls nE
1. soc*t fun.tion
3, Red
5. clo5e
> secrElllllcrlaE
Ihe tunctlon ts @lled to 6ead. a socket to Perform client s er applitton
*lncl;de<EYr/tock't h>
lnt 6o.k.t(ha famitY, lnt tvp', ht DEtodl);
! ReLurns non negdnve descnptor ifoR

. qam,'y - sp(mes the proto(olfamilv.


3. AF lNET-lPv4 Protocol
4. AFJNET5_IPV6 Proto@l
! TYPe - speifles the socket tYPe
l StEn - U*d for TCP Conne'tlon
Socket (SOCK-STREAM)
2.Dataq6m Sockt (soclqDcRAln) - Used for UDP connectlon
& uDP &ICMP'
3.Raw Socket (sOC( RAw) - Ured ror ooth TCP
t Pbtcd - et to o

EACCES Peftislon to cEte socket is denied

The system h.s no av6llable buffer space'

ME. s. Anheeswan AP/IT, MEc


Mr. P. Saravanan APlIr, MEC
IT 2351 / I'IETWORK PROGRA',IMIiIG AI{D MANAGEMEM

'

socKEr(

tus;EN,l l
socKET( )

CoNNECT( )

Blocks unulconnction

WRITE( l

closE( )

> THE OOX ECTCALL:


The connect functlon is usd by a TCP ctient to *rabtish a connecrion with a TCP
*hclud.<ry./uket.h>
lnt @mect(aot $cktd,co.st stru.t so.haddr *.eru:ddrr sockt.r_t

, Socktd-> socket descnptor vatue.


. ServaddF pointerto socket addrGs stru.ture. the socket address
structure mustcoitain the IPaddre$ and port number ofthe

' addrleh-> Lenqth o lnte setuer add.ess,

Prcparcd By: MB. s. Artheeswari Ap/lT. MEc PaBe 35


Mr. P. Saravanan AP/IT, MEC
ur,lfT-1
23511 NETWORK PROGRAMI4II{6 AND I'4ANAGEMEII

r.r.t a valid socket d escripto r


Il the firstargsment is notspecified.
EISCONN tf the socket isalreadv connected.
EIIMEDOUT rf the @nnection is not establlshd
If th port number specjfied is not w.iting on the setuer for

when the destlnatio. is unEachable frcm some intemedlate

CIOSE FUNCTION:
rt is used to close the socket a nd terminate a TcP corn4tion'
+i6.lude<unBtd.h>
intclo.e(ht sockerd);
. tt Ptlrn o if oK

Itmarks the sockt as clGed and return to the pbcss lmmdiatelv'


The $cket de*rlptoris no longerusable bv th pb@s , it
be
'annot
used as an srqument to ead o.wnte
to be *nt to the
But TcP wlll try tD *nd anv data that ls alradv quued

. tl s dP nom.l TcP @nn4tjon lemlnation *quene takes plae'

p*
Alter
ln d.Lll th. ...*.t turcdont for .lem'nt'rv TcP lutctloB
wlth
Expt.In '
SCEIIARIO BETWEE fHE CllCI{T AIID SCRVER:
FEt the seNer' is sta.ted tne. sometin later a client is started that
the seler pro(e*
@nnects to a seru.r. 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 .otifiGtton
then dos its end of the connectron and either tetminates
or
sder. The *Ner
(alt5 lor a ns client@nn4tlon.

i[-oma gviii. s. a,t'."sdair AP,m, I'aEc Prse 36


Mr P s:ravanan aP/tT, MEC
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 .reat a soCiet to perform ctient s erapploflon.
#tr.tude<syslso.ket.h>
int .o.ket(inr famlly, irt type, intprctocot);
Retums non negative descriptor if OK,

Fami,y - spcifies the prctocot famity.


5. AF IIEI-IPV4 protocol
6. AF_INET5 rPV6 protocot
Type - specifi the socket type,
1.StEm Soclet (sock_sTREAI.4) - used for rcP connection
2.DatagEm Socket (SOCK DGRAI4) - Used for UDPConnection
3.Raw Socket (Socx-MW) - used for both Tcp & uDp & rcMp.

PEpared Ey: l4rs, S. Anheeswari AplIr, i4EC


I4r, P. SaravrnanAP/fi, MEC
N / NETWORT PROGMI,II'4ING AND MANACEYENT UNII'I
'35I
Prctocol- set to 0.

Permiision to .rea6 socket is denred.


ft $stem has no avallable bufrer spa.e. I
I

EIlLEUlgUalr
the bind tunctlon a$rgc a l@l pDtc.l addE5 to a sd*et . intemet pbto@l
add6 ls a @mbinEtion of nner 32 bt tPv4 addls or 123 bats lPv6 addlEs alonq
wlth a 16 b'ts ICP or UOP port numtcr
irt bind(irt $cldd, @n3t 3tr!d *kaddr .my.ddr, *.klen-t .ddrl.n);
o It Eturns 0 if OX & -1on e@r
o socnid- socket decnpnon
o My addr theaddre$ ofa structure that specifies an lp addr6sand port

o Addrlen- Th size of the addres structue in bytes.


R.turn code:
Rerurn 0 if su@sstul & -1on erbi

Not a valld socketd6criptor


ENOTSOCK If the fiEt argument is rot speclfied.
If the adds ls already bou.d to it
lf the locladdress arqument polnter is Invalid.

Kernel choces lP Eddress and port

net ct ose Ipaaaesuna poessspcifies Port

Poces sp<lfis IP address, kernelchooses port

Pro@ss specifies the lP address & pon

> I!!-!EII!-c4!!r
It is 6led only byaTcPse erand it prforms twofunctions.

Prcpared By: l.!8. S. Atheesari AP/IT, ilEC


Mi P. Sa6vanan aPllI, l'4Ec
tI 2351 / I{ETWORK PROGMMMIiIG AI'ID MANAGEI'4EI,IT

3. The listentun*Dn mnverts an un.onne.ied socket tnto a passtvesocket


indictlng that the kernel shoutd a..ept rhe incomrnq.onne.non requesr
d,rected to ihls socket.
a, ftspecJfies the maximum number otconnecuon rhe kernershoutd q!e!efor

sin.lude <sys/so.kt.h>
ht ll.ten (int .o.kfd, htbacktoq);
, It retlrn 0 tfOK, -1on errcr.
The kernelmainteins two queues:
5, In@mplete 6nndion oueue:
It.ontains an entry for each sYN rhat artved lrom a ctient for which the
sererls awaltinq.ompletlon olthe three way handshake.
6. Completed 6nnedion oueuei
It @ntainsan entry for ea.h ctientwirh the TCp three way handshake has

Socldd- &det d@iptor


Backlog- size of tn@mtng 6ne.non eqne.a.

Not a valld wket dediptor


r the f6t aqument is not sp4ified.

> THE ACCCEY FUI{CIIOI{:


The a@pt is @lled by the TCP e er to etum rhe next @mpteted 6nnd.Uon
from the frorr of tlre .ompleted conoecuon queue. Accpt creat a ner socket and
Eturn the descriptorofthe new socket to rhe caller. rhe servercan tr.nsfer data on
the new socket afier fintshinq the s er closes it.
#in.lud. <sys/3o.k Lh>
int .cccpt (int Eocldd, struct so.k.ddr *.tt.ddr, .ockten_t .ddrt.n);
t Non ngattve dscriptor rfOK
t Else -1 on eror
Socktd-> socket descriptor
cliaddF> client IP address
addnen-> ehgth ofthe second arlumenr,
Ihe @nnected socket is closed each ttinewhilethe ltstenjng so.ket
remalns open for the litu of the seryer. Thts ts supported only tn stEam.

PreD.rcd Bv: M6. S, Artheeswari Ap/IT, l.4EC Page 39


r.4r. p. Saravanan AplIT, MEC
rr 23s1 / NErwoRK pRoGMM,,4rNG aNo r4Alg-y.g

Not a valid ecket dedlptor


ENOTSOCK rthe firet argument 15 not specified.
so.ker is nora socKET STREAM.

Th...n.edtundlon is used bY aTCPclintto establish a wlth a rCP


'onnection
*in.lude<.yslsock.t.h>
lntcornect(Int$ckfdt.orst3trucl.4haddt*sd.ddr, todd'n-t
aildrlen);

o El*_1one or
. Sockfd-> so.kel des.dptot value.
. sewaddts pointer to ecket address structure the scket addls
- sttudure must @ntaln the tP addre* and port 'umber of the

. addrln-> Lensth o fhte $Ner address

Not a valld soclet dsc,iDtor


rthe fiBt argument E not specined.
lf the ecket ls akeadv @nnected.
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.din.tlon is unreach6ble ftum $me lntermedl'ie

> crrosE FUI{CIIOX:


ft is used to de the so.ket sid temioate a TcP connectlon
tl.d!dc<untstd'n>
ht clce(lnt $ctcfd)i

It marks the sodGt as.losed and tum to the pb'ess lmmedlatelv'


The socket dsriptor as no lonqer u*ble by the
prc'ess , 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,

Prc!.red By ! ltlrs. s adheesan AP/rr, MEC


Mi P. Sahvanan APIIT, MEC
N 7351 / NETWqRX PROCRAI.IMING AND AIAGEMEMT UNTT.T
:
.
;\fter this the nomat TCp connedion termlnation sequene takes ptae.
11. Comp.r. tfte rpv4, tpv6, UnrX domair .nd datatink 3o.ket address
.lrqdtrE, .t t. your .$uhptto.r
SOCKEI ADDRESS STRUCTURES
' Each prctocol suit defin4 lts own scket addE$ stiuctures. Ile
name of the strudure begins wlth sockaddr ,

Varicus ecket address qtrudurpc ;r.


I. Cenenc Socket Add.6s structure
2, IPv4 Socket Address Srru.iure
3. IPv5 SockFt Acdress Srru L?
/ GENERIC SOCXET ADDRESS SIRUCTURE

{
./
/* length of the structle
s_fahlly_t sa_family; /r addB t mily : ,.F xlx value
/* pret@l specrfic addre$ r/

7 lDva SOGIET rpDlESs sr rctutE ton) rERnEr soa(Er AppREsS


slnucruRE t m.

strud $ckaddr in
t
uint8t sln_lenj /r length ofthe structure */
*_fdmily,t siLfamfly; /* AF_aNET */
rn_irorlt sinJ)on; /* 16 blt pori'/
struct in_addr sln_addr; /, 32 btt lpv4 addres in aetwork order */
.hdrsh_zerol3l; /* thusedt/
j',

{
in_addr_t s_addr; /.32 bitlpv4 address tn netwoik byte orde.*/
1,

PrcparEd By ! M6. s. Artheeswan AP/IT, I,4Ec


rti., P. sar6vanan Apll1, rr4Ec
IT 2]5T , I{ETWORK PROGMMI'IING ANO II4ANACLMEIIT UNTT.I

/ IPI'6 SOCKET ADDRESS STTUCTURE

SIN6-LEN /r recutred f6rcomprle nme tesEr/

{
/* rensth or the structuB */
e_fanily t sin6-famlly;
/* TransDort Laver port in Net{oft Byte order
/*Pdonty &flow label in netwo.k btte ordered
strucr in6_addrl.6 addr i /* IPv6 address in network byte order
r/

);

r' @I.PAIISOX OF SaCXEI ADDRESS STRUCIURE


1Pr4 !86 !J!IX

12. Explain .ny tiB. .ddB. .onvcrsloD fun.tion. in det.ll. (riAY 2012)

RererQ. o.04
13. Expl.in in detall th.5o.ket functions lnvolv.d ln a ba.lc lcP .llni sry6r
(irAY2012)
Refer Q. No, r0

P-t"*d Ey.. l'-j..s. artt".sv,ari AP/IT, MEC PaEe42


Mr. P. saravahan AP/F, I4Ec
f
-l II2351 / ITENYORX PROGRAMIiING AT{D MANAGEMETIT UNTT.1

14, E(plain TcP Connectlor BtabliEhment.nd Trmitratton wtth. neat.kctch.


(itaY20r2)
r' TCF COI{NECIIOT{ EST ELISHMEIIII, a thEe ws H.ndrh.k.r

Socket, Connect (blocks)

The se er must b pEp.rd to .aept an rn6min9 @n6tion. Ttis is


normally done by cllins ecket, brnd and risten. This is crred as

The Client isues.n a.tive open by ottilE @EE<t, This 6U*


the .llent TCP to end a sYN (SF6miz) eglrbr to lel tne serye.
tle clie.t's inrtralsequene numb.. io. t E data that the clent wi send
on the onnectlon. No d.ta rs *m with SYN. It contEins onty tP
Hsderr TCP Header and po$ible TcP optlons,
The * er must a.lrowledg. tne dtents SYN and the seruer must ste
*nd lts own SYN drbrr{,B tlE initirt s.quen@ number for the
data that the 5e sldi The ere. d$ .ends the a.knowtedgement
of the cllenls sYN in a srngte *dRnt.
The cl,ent must adarMtedse tie *re/s syN,
l1re manmum number of paclets EqutEd for the exchange B
th.ee/ hen@thls is @lled as three - way handshake.
> IGE-9eIIA!SI
me$age @ntalns TCP options such as
1

1, llSS Opnon I Maxlmlm Segment Slze , TCP MAXSEG


wlndow S6le Optlon . The maximum wlndow size that tae -rcP @n
advertise to other TcP ls 6s535.
3. Tlmestamo Option i Needed ror hlsh sped @nneuons to orevent
posslble data corruptlon caused by lost packets

Prepard By I IvtB, S, Artheeswart AP/IT, MEC


lvr, P. Saravanan APIIT, MEC
I
MTNC AND MANACLIVE - IJNTT I

TCPCONI'IECIION TER INAAION :

TCp uses four segments to terfrinate the.o.nection.


The.ltent@lls close and performs active .lose. TCP sends FIN segmnt'
The seruer ecelvG the FIN and perfofms the passive close. The r*lved
FIN s acknowledged by rcP.
THE seNer *nds the FIN segment to the cllent
The cllent acknowledges the aN seEment eeived from se er and frnallv
bmrnateE the onnection,

15. DEw . TcP .odct ltow dlagr.d .nd qplain thc functloB. (DEC 2O1t)

Rerer Q. o. 10
15. E)9Lb! ttE noflorlng ln .let ll:
(D n n rE *r.l
(fi) cdEllgt$rui (DEC 2011)

Refer Q. flo.3

_
r"po.a gy , uo, s, erth*rr p/rr, ltc Fage 44
Mr. P. sarcvdin APlfi, MK