TutorialsPoint - Unix Socket Quick Guide
TutorialsPoint - Unix Socket Quick Guide
UnixSocketQuickGuide
UnixSocketQuickGuide
https://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm
Copyrighttutorialspoint.com
WhatisaSocket?
Socketsallowcommunicationbetweentwodifferentprocessesonthesameordifferentmachines.Tobemore
precise,it'sawaytotalktoothercomputersusingstandardUnixfiledescriptors.InUnix,everyI/Oactionisdoneby
writingorreadingafiledescriptor.Afiledescriptorisjustanintegerassociatedwithanopenfileanditcanbea
networkconnection,atextfile,aterminal,orsomethingelse.
Toaprogrammer,asocketlooksandbehavesmuchlikealowlevelfiledescriptor.Thisisbecausecommandssuchas
read()andwrite()workwithsocketsinthesamewaytheydowithfilesandpipes.
Socketswerefirstintroducedin2.1BSDandsubsequentlyrefinedintotheircurrentformwith4.2BSD.Thesockets
featureisnowavailablewithmostcurrentUNIXsystemreleases.
WhereisSocketUsed?
AUnixSocketisusedinaclientserverapplicationframework.Aserverisaprocessthatperformssomefunctionson
requestfromaclient.MostoftheapplicationlevelprotocolslikeFTP,SMTP,andPOP3makeuseofsocketsto
establishconnectionbetweenclientandserverandthenforexchangingdata.
SocketTypes
Therearefourtypesofsocketsavailabletotheusers.Thefirsttwoaremostcommonlyusedandthelasttwoare
rarelyused.
Processesarepresumedtocommunicateonlybetweensocketsofthesametypebutthereisnorestrictionthat
preventscommunicationbetweensocketsofdifferenttypes.
StreamSocketsDeliveryinanetworkedenvironmentisguaranteed.Ifyousendthroughthestreamsocket
threeitems"A,B,C",theywillarriveinthesameorder"A,B,C".ThesesocketsuseTCP(Transmission
ControlProtocol)fordatatransmission.Ifdeliveryisimpossible,thesenderreceivesanerrorindicator.Data
recordsdonothaveanyboundaries.
DatagramSocketsDeliveryinanetworkedenvironmentisnotguaranteed.They'reconnectionlessbecause
youdon'tneedtohaveanopenconnectionasinStreamSocketsyoubuildapacketwiththedestination
informationandsenditout.TheyuseUDP(UserDatagramProtocol).
RawSocketsTheseprovideusersaccesstotheunderlyingcommunicationprotocols,whichsupportsocket
abstractions.Thesesocketsarenormallydatagramoriented,thoughtheirexactcharacteristicsaredependenton
theinterfaceprovidedbytheprotocol.Rawsocketsarenotintendedforthegeneralusertheyhavebeen
providedmainlyforthoseinterestedindevelopingnewcommunicationprotocols,orforgainingaccesstosome
ofthemorecrypticfacilitiesofanexistingprotocol.
SequencedPacketSocketsTheyaresimilartoastreamsocket,withtheexceptionthatrecordboundariesare
preserved.ThisinterfaceisprovidedonlyasapartoftheNetworkSystems(NS)socketabstraction,andisvery
importantinmostseriousNSapplications.Sequencedpacketsocketsallowtheusertomanipulatethe
SequencePacketProtocol(SPP)orInternetDatagramProtocol(IDP)headersonapacketoragroupof
packets,eitherbywritingaprototypeheaderalongwithwhateverdataistobesent,orbyspecifyingadefault
headertobeusedwithalloutgoingdata,andallowstheusertoreceivetheheadersonincomingpackets.
WhatisNext?
https://www.tutorialspoint.com/cgibin/printpage.cgi
1/26
12/11/2016
UnixSocketQuickGuide
ThenextfewchaptersaremeanttostrengthenyourbasicsandprepareafoundationbeforeyoucanwriteServerand
Clientprogramsusingsocket.Ifyoudirectlywanttojumptoseehowtowriteaclientandserverprogram,thenyou
candosobutitisnotrecommended.Itisstronglyrecommendedthatyougostepbystepandcompletetheseinitial
fewchapterstomakeyourbasebeforemovingontodoprogramming.
UnixSocketNetworkAddresses
Beforeweproceedwiththeactualstuff,letusdiscussabitabouttheNetworkAddressestheIPAddress.
TheIPhostaddress,ormorecommonlyjustIPaddress,isusedtoidentifyhostsconnectedtotheInternet.IPstands
forInternetProtocolandreferstotheInternetLayeroftheoverallnetworkarchitectureoftheInternet.
AnIPaddressisa32bitquantityinterpretedas48bitnumbersoroctets.EachIPaddressuniquelyidentifiesthe
participatingusernetwork,thehostonthenetwork,andtheclassoftheusernetwork.
AnIPaddressisusuallywritteninadotteddecimalnotationoftheformN1.N2.N3.N4,whereeachNiisadecimal
numberbetween0and255decimal(00throughFFhexadecimal).
AddressClasses
IPaddressesaremanagedandcreatedbytheInternetAssignedNumbersAuthority(IANA).Therearefivedifferent
addressclasses.YoucandeterminewhichclassanIPaddressisinbyexaminingthefirstfourbitsoftheIPaddress.
ClassAaddressesbeginwith0xxx,or1to126decimal.
ClassBaddressesbeginwith10xx,or128to191decimal.
ClassCaddressesbeginwith110x,or192to223decimal.
ClassDaddressesbeginwith1110,or224to239decimal.
ClassEaddressesbeginwith1111,or240to254decimal.
Addressesbeginningwith01111111,or127decimal,arereservedforloopbackandforinternaltestingonalocal
machine[Youcantestthis:youshouldalwaysbeabletoping127.0.0.1,whichpointstoyourself]ClassDaddresses
arereservedformulticastingClassEaddressesarereservedforfutureuse.Theyshouldnotbeusedforhost
addresses.
Example
Class Leftmostbits Startaddress Finishaddress
A
0xxx
0.0.0.0
127.255.255.255
B
10xx
128.0.0.0
191.255.255.255
C
110x
192.0.0.0
223.255.255.255
D
1110
224.0.0.0
239.255.255.255
E
1111
240.0.0.0
255.255.255.255
Subnetting
Subnettingorsubnetworkingbasicallymeanstobranchoffanetwork.Itcanbedoneforavarietyofreasonslike
networkinanorganization,useofdifferentphysicalmedia(suchasEthernet,FDDI,WAN,etc.),preservationof
addressspace,andsecurity.Themostcommonreasonistocontrolnetworktraffic.
ThebasicideainsubnettingistopartitionthehostidentifierportionoftheIPaddressintotwoparts
Asubnetaddresswithinthenetworkaddressitselfand
Ahostaddressonthesubnet.
https://www.tutorialspoint.com/cgibin/printpage.cgi
2/26
12/11/2016
UnixSocketQuickGuide
Forexample,acommonClassBaddressformatisN1.N2.S.H,whereN1.N2identifiestheClassBnetwork,the8bit
Sfieldidentifiesthesubnet,andthe8bitHfieldidentifiesthehostonthesubnet.
UnixSocketNetworkHostNames
Hostnamesintermsofnumbersaredifficulttorememberandhencetheyaretermedbyordinarynamessuchas
TakshilaorNalanda.WewritesoftwareapplicationstofindoutthedottedIPaddresscorrespondingtoagivenname.
TheprocessoffindingoutdottedIPaddressbasedonthegivenalphanumerichostnameisknownashostname
resolution.
Ahostnameresolutionisdonebyspecialsoftwareresidingonhighcapacitysystems.Thesesystemsarecalled
DomainNameSystems(DNS),whichkeepthemappingofIPaddressesandthecorrespondingordinarynames.
The/etc/hostsFile
ThecorrespondencebetweenhostnamesandIPaddressesismaintainedinafilecalledhosts.Onmostofthesystems,
thisfileisfoundin/etcdirectory.
Entriesinthisfilelooklikethefollowing
#Thisrepresentsacommentsin/etc/hostsfile.
127.0.0.1localhost
192.217.44.207nalandametro
153.110.31.18netserve
153.110.31.19mainservercenteral
153.110.31.20samsonite
64.202.167.10ns3.secureserver.net
64.202.167.97ns4.secureserver.net
66.249.89.104www.google.com
68.178.157.132services.amrood.com
NotethatmorethanonenamemaybeassociatedwithagivenIPaddress.ThisfileisusedwhileconvertingfromIP
addresstohostnameandviceversa.
Youwouldnothaveaccesstoeditthisfile,soifyouwanttoputanyhostnamealongwithIPaddress,thenyouwould
needtohaverootpermission.
UnixSocketClientServerModel
MostoftheNetApplicationsusetheClientServerarchitecture,whichreferstotwoprocessesortwoapplications
thatcommunicatewitheachothertoexchangesomeinformation.Oneofthetwoprocessesactsasaclientprocess,
andanotherprocessactsasaserver.
ClientProcess
Thisistheprocess,whichtypicallymakesarequestforinformation.Aftergettingtheresponse,thisprocessmay
terminateormaydosomeotherprocessing.
Example,InternetBrowserworksasaclientapplication,whichsendsarequesttotheWebServertogetoneHTML
webpage.
ServerProcess
Thisistheprocesswhichtakesarequestfromtheclients.Aftergettingarequestfromtheclient,thisprocesswill
performtherequiredprocessing,gathertherequestedinformation,andsendittotherequestorclient.Oncedone,it
becomesreadytoserveanotherclient.Serverprocessesarealwaysalertandreadytoserveincomingrequests.
ExampleWebServerkeepswaitingforrequestsfromInternetBrowsersandassoonasitgetsanyrequestfroma
browser,itpicksuparequestedHTMLpageandsendsitbacktothatBrowser.
https://www.tutorialspoint.com/cgibin/printpage.cgi
3/26
12/11/2016
UnixSocketQuickGuide
Notethattheclientneedstoknowtheaddressoftheserver,buttheserverdoesnotneedtoknowtheaddressoreven
theexistenceoftheclientpriortotheconnectionbeingestablished.Onceaconnectionisestablished,bothsidescan
sendandreceiveinformation.
2tierand3tierarchitectures
Therearetwotypesofclientserverarchitectures
2tierarchitectureInthisarchitecture,theclientdirectlyinteractswiththeserver.Thistypeofarchitecture
mayhavesomesecurityholesandperformanceproblems.InternetExplorerandWebServerworkontwotier
architecture.HeresecurityproblemsareresolvedusingSecureSocketLayer(SSL).
3tierarchitecturesInthisarchitecture,onemoresoftwaresitsinbetweentheclientandtheserver.This
middlesoftwareiscalledmiddleware.Middlewareareusedtoperformallthesecuritychecksandload
balancingincaseofheavyload.Amiddlewaretakesallrequestsfromtheclientandafterperformingthe
requiredauthentication,itpassesthatrequesttotheserver.Thentheserverdoestherequiredprocessingand
sendstheresponsebacktothemiddlewareandfinallythemiddlewarepassesthisresponsebacktotheclient.If
youwanttoimplementa3tierarchitecture,thenyoucankeepanymiddlewarelikeWebLogicorWebSphere
softwareinbetweenyourWebServerandWebBrowser.
TypesofServer
Therearetwotypesofserversyoucanhave
IterativeServerThisisthesimplestformofserverwhereaserverprocessservesoneclientandafter
completingthefirstrequest,ittakesrequestfromanotherclient.Meanwhile,anotherclientkeepswaiting.
ConcurrentServersThistypeofserverrunsmultipleconcurrentprocessestoservemanyrequestsatatime
becauseoneprocessmaytakelongerandanotherclientcannotwaitforsolong.Thesimplestwaytowritea
concurrentserverunderUnixistoforkachildprocesstohandleeachclientseparately.
HowtoMakeClient
Thesystemcallsforestablishingaconnectionaresomewhatdifferentfortheclientandtheserver,butbothinvolve
thebasicconstructofasocket.Boththeprocessesestablishtheirownsockets.
Thestepsinvolvedinestablishingasocketontheclientsideareasfollows
Createasocketwiththesocket()systemcall.
Connectthesockettotheaddressoftheserverusingtheconnect()systemcall.
Sendandreceivedata.Thereareanumberofwaystodothis,butthesimplestwayistousetheread()and
write()systemcalls.
HowtomakeaServer
Thestepsinvolvedinestablishingasocketontheserversideareasfollows
Createasocketwiththesocket()systemcall.
Bindthesockettoanaddressusingthebind()systemcall.ForaserversocketontheInternet,anaddress
consistsofaportnumberonthehostmachine.
Listenforconnectionswiththelisten()systemcall.
Acceptaconnectionwiththeaccept()systemcall.Thiscalltypicallyblockstheconnectionuntilaclient
connectswiththeserver.
Sendandreceivedatausingtheread()andwrite()systemcalls.
https://www.tutorialspoint.com/cgibin/printpage.cgi
4/26
12/11/2016
UnixSocketQuickGuide
ClientandServerInteraction
FollowingisthediagramshowingthecompleteClientandServerinteraction
UnixSocketStructures
VariousstructuresareusedinUnixSocketProgrammingtoholdinformationabouttheaddressandport,andother
information.Mostsocketfunctionsrequireapointertoasocketaddressstructureasanargument.Structuresdefined
inthischapterarerelatedtoInternetProtocolFamily.
sockaddr
Thefirststructureissockaddrthatholdsthesocketinformation
structsockaddr{
unsignedshortsa_family;
charsa_data[14];
};
Thisisagenericsocketaddressstructure,whichwillbepassedinmostofthesocketfunctioncalls.Thefollowing
tableprovidesadescriptionofthememberfields
Attribute
Values
Description
AF_INET
https://www.tutorialspoint.com/cgibin/printpage.cgi
5/26
12/11/2016
UnixSocketQuickGuide
AF_UNIX
sa_family
AF_NS
Itrepresentsanaddressfamily.InmostoftheInternetbasedapplications,weuse
AF_INET.
AF_IMPLINK
sa_data
Protocol
specific
Address
Thecontentofthe14bytesofprotocolspecificaddressareinterpretedaccordingtothe
typeofaddress.FortheInternetfamily,wewilluseportnumberIPaddress,whichis
representedbysockaddr_instructuredefinedbelow.
sockaddrin
Thesecondstructurethathelpsyoutoreferencetothesocket'selementsisasfollows
structsockaddr_in{
shortintsin_family;
unsignedshortintsin_port;
structin_addrsin_addr;
unsignedcharsin_zero[8];
};
Hereisthedescriptionofthememberfields
Attribute
Values
Description
AF_INET
sa_family
AF_UNIX
AF_NS
Itrepresentsanaddressfamily.InmostoftheInternetbasedapplications,weuse
AF_INET.
AF_IMPLINK
sin_port ServicePort
sin_addr IPAddress
sin_zero NotUsed
A16bitportnumberinNetworkByteOrder.
A32bitIPaddressinNetworkByteOrder.
YoujustsetthisvaluetoNULLasthisisnotbeingused.
inaddr
Thisstructureisusedonlyintheabovestructureasastructurefieldandholds32bitnetid/hostid.
structin_addr{
unsignedlongs_addr;
};
Hereisthedescriptionofthememberfields
Attribute Values
Description
s_addr
serviceport A32bitIPaddressinNetworkByteOrder.
hostent
Thisstructureisusedtokeepinformationrelatedtohost.
structhostent{
char*h_name;
char**h_aliases;
inth_addrtype;
inth_length;
char**h_addr_list
https://www.tutorialspoint.com/cgibin/printpage.cgi
6/26
12/11/2016
UnixSocketQuickGuide
#defineh_addrh_addr_list[0]
};
Hereisthedescriptionofthememberfields
Attribute
Values
Description
ti.com
h_name
Itistheofficialnameofthehost.Forexample,tutorialspoint.com,google.com,etc.
etc.
h_aliases TI
Itholdsalistofhostnamealiases.
ItcontainstheaddressfamilyandincaseofInternetbasedapplication,itwillalwaysbe
h_addrtype AF_INET
AF_INET.
h_length 4
ItholdsthelengthoftheIPaddress,whichis4forInternetAddress.
ForInternetaddresses,thearrayofpointersh_addr_list[0],h_addr_list[1],andsoon,are
h_addr_list in_addr
pointstostructurein_addr.
NOTEh_addrisdefinedash_addr_list[0]tokeepbackwardcompatibility.
servent
Thisparticularstructureisusedtokeepinformationrelatedtoserviceandassociatedports.
structservent{
char*s_name;
char**s_aliases;
ints_port;
char*s_proto;
};
Hereisthedescriptionofthememberfields
Attribute Values
Description
s_name http
Thisistheofficialnameoftheservice.Forexample,SMTP,FTPPOP3,etc.
s_aliases ALIAS Itholdsthelistofservicealiases.MostofthetimethiswillbesettoNULL.
s_port
80
Itwillhaveassociatedportnumber.Forexample,forHTTP,thiswillbe80.
s_proto
TCP
UDP
Itissettotheprotocolused.InternetservicesareprovidedusingeitherTCPorUDP.
TipsonSocketStructures
Socketaddressstructuresareanintegralpartofeverynetworkprogram.Weallocatethem,fillthemin,andpass
pointerstothemtovarioussocketfunctions.Sometimeswepassapointertooneofthesestructurestoasocket
functionanditfillsinthecontents.
Wealwayspassthesestructuresbyreference(i.e.,wepassapointertothestructure,notthestructureitself),andwe
alwayspassthesizeofthestructureasanotherargument.
Whenasocketfunctionfillsinastructure,thelengthisalsopassedbyreference,sothatitsvaluecanbeupdatedby
thefunction.Wecallthesevalueresultarguments.
Always,setthestructurevariablestoNULL(i.e.,'\0')byusingmemset()forbzero()functions,otherwiseitmayget
unexpectedjunkvaluesinyourstructure.
UnixSocketPortsandServices
Whenaclientprocesswantstoaconnectaserver,theclientmusthaveawayofidentifyingtheserverthatitwantsto
connect.Iftheclientknowsthe32bitInternetaddressofthehostonwhichtheserverresides,itcancontactthathost.
https://www.tutorialspoint.com/cgibin/printpage.cgi
7/26
12/11/2016
UnixSocketQuickGuide
Buthowdoestheclientidentifytheparticularserverprocessrunningonthathost?
Toresolvetheproblemofidentifyingaparticularserverprocessrunningonahost,bothTCPandUDPhavedefineda
groupofwellknownports.
Forourpurpose,aportwillbedefinedasanintegernumberbetween1024and65535.Thisisbecauseallport
numberssmallerthan1024areconsideredwellknownforexample,telnetusesport23,httpuses80,ftpuses21,
andsoon.
Theportassignmentstonetworkservicescanbefoundinthefile/etc/services.Ifyouarewritingyourownserver
thencaremustbetakentoassignaporttoyourserver.Youshouldmakesurethatthisportshouldnotbeassignedto
anyotherserver.
Normallyitisapracticetoassignanyportnumbermorethan5000.Buttherearemanyorganizationswhohave
writtenservershavingportnumbersmorethan5000.Forexample,YahooMessengerrunson5050,SIPServerruns
on5060,etc.
ExamplePortsandServices
Hereisasmalllistofservicesandassociatedports.Youcanfindthemostupdatedlistofinternetportsandassociated
serviceatIANATCP/IPPortAssignments.
Service PortNumber
echo
7
discard 9
daytime 13
chargen 19
ftp
21
telnet 23
smtp
25
daytime 37
tftp
69
finger 79
http
80
login 513
who
513
Xserver 6000
ServiceDescription
UDP/TCPsendsbackwhatitreceives.
UDP/TCPthrowsawayinput.
UDP/TCPreturnsASCIItime.
UDP/TCPreturnscharacters.
TCPfiletransfer.
TCPremotelogin.
TCPemail.
UDP/TCPreturnsbinarytime.
UDPtrivialfiletransfer.
TCPinfoonusers.
TCPWorldWideWeb.
TCPremotelogin.
UDPdifferentinfoonusers.
TCPXwindows(N.B.>1023).
PortandServiceFunctions
Unixprovidesthefollowingfunctionstofetchservicenamefromthe/etc/servicesfile.
structservent*getservbyname(char*name,char*proto)Thiscalltakesservicenameandprotocolname,
andreturnsthecorrespondingportnumberforthatservice.
structservent*getservbyport(intport,char*proto)Thiscalltakesportnumberandprotocolname,and
returnsthecorrespondingservicename.
Thereturnvalueforeachfunctionisapointertoastructurewiththefollowingform
structservent{
char*s_name;
char**s_aliases;
ints_port;
char*s_proto;
};
Hereisthedescriptionofthememberfields
https://www.tutorialspoint.com/cgibin/printpage.cgi
8/26
12/11/2016
UnixSocketQuickGuide
Attribute Values
Description
s_name http
Itistheofficialnameoftheservice.Forexample,SMTP,FTPPOP3,etc.
s_aliases ALIAS Itholdsthelistofservicealiases.Mostofthetime,itwillbesettoNULL.
s_port
80
Itwillhavetheassociatedportnumber.Forexample,forHTTP,itwillbe80.
s_proto
TCP
UDP
Itissettotheprotocolused.InternetservicesareprovidedusingeitherTCPorUDP.
UnixSocketNetworkByteOrders
Unfortunately,notallcomputersstorethebytesthatcompriseamultibytevalueinthesameorder.Considera16bit
internetthatismadeupof2bytes.Therearetwowaystostorethisvalue.
LittleEndianInthisscheme,loworderbyteisstoredonthestartingaddress(A)andhighorderbyteis
storedonthenextaddress(A+1).
BigEndianInthisscheme,highorderbyteisstoredonthestartingaddress(A)andloworderbyteisstored
onthenextaddress(A+1).
Toallowmachineswithdifferentbyteorderconventionscommunicatewitheachother,theInternetprotocolsspecify
acanonicalbyteorderconventionfordatatransmittedoverthenetwork.ThisisknownasNetworkByteOrder.
WhileestablishinganInternetsocketconnection,youmustmakesurethatthedatainthesin_portandsin_addr
membersofthesockaddr_instructurearerepresentedinNetworkByteOrder.
ByteOrderingFunctions
Routinesforconvertingdatabetweenahost'sinternalrepresentationandNetworkByteOrderareasfollows
Function
Description
htons() HosttoNetworkShort
htonl() HosttoNetworkLong
ntohl() NetworktoHostLong
ntohs() NetworktoHostShort
Listedbelowaresomemoredetailaboutthesefunctions
unsignedshorthtons(unsignedshorthostshort)Thisfunctionconverts16bit(2byte)quantitiesfromhost
byteordertonetworkbyteorder.
unsignedlonghtonl(unsignedlonghostlong)Thisfunctionconverts32bit(4byte)quantitiesfromhost
byteordertonetworkbyteorder.
unsignedshortntohs(unsignedshortnetshort)Thisfunctionconverts16bit(2byte)quantitiesfrom
networkbyteordertohostbyteorder.
unsignedlongntohl(unsignedlongnetlong)Thisfunctionconverts32bitquantitiesfromnetworkbyte
ordertohostbyteorder.
Thesefunctionsaremacrosandresultintheinsertionofconversionsourcecodeintothecallingprogram.Onlittle
endianmachines,thecodewillchangethevaluesaroundtonetworkbyteorder.Onbigendianmachines,nocodeis
insertedsincenoneisneededthefunctionsaredefinedasnull.
ProgramtoDetermineHostByteOrder
Keepthefollowingcodeinafilebyteorder.candthencompileitandrunitoveryourmachine.
https://www.tutorialspoint.com/cgibin/printpage.cgi
9/26
12/11/2016
UnixSocketQuickGuide
Inthisexample,westorethetwobytevalue0x0102intheshortintegerandthenlookatthetwoconsecutivebytes,
c[0](theaddressA)andc[1](theaddressA+1)todeterminethebyteorder.
#include<stdio.h>
intmain(intargc,char**argv){
union{
shorts;
charc[sizeof(short)];
}un;
un.s=0x0102;
if(sizeof(short)==2){
if(un.c[0]==1&&un.c[1]==2)
printf("bigendian\n");
elseif(un.c[0]==2&&un.c[1]==1)
printf("littleendian\n");
else
printf("unknown\n");
}
else{
printf("sizeof(short)=%d\n",sizeof(short));
}
exit(0);
}
AnoutputgeneratedbythisprogramonaPentiummachineisasfollows
$>gccbyteorder.c
$>./a.out
littleendian
$>
UnixSocketIPAddressFunctions
UnixprovidesvariousfunctioncallstohelpyoumanipulateIPaddresses.ThesefunctionsconvertInternetaddresses
betweenASCIIstrings(whathumansprefertouse)andnetworkbyteorderedbinaryvalues(valuesthatarestoredin
socketaddressstructures).
ThefollowingthreefunctioncallsareusedforIPv4addressing
intinet_aton(constchar*strptr,structin_addr*addrptr)
in_addr_tinet_addr(constchar*strptr)
char*inet_ntoa(structin_addrinaddr)
intinet_aton(constchar*strptr,structin_addr*addrptr)
ThisfunctioncallconvertsthespecifiedstringintheInternetstandarddotnotationtoanetworkaddress,andstores
theaddressinthestructureprovided.TheconvertedaddresswillbeinNetworkByteOrder(bytesorderedfromleft
toright).Itreturns1ifthestringwasvalidand0onerror.
Followingistheusageexample
#include<arpa/inet.h>
(...)
intretval;
structin_addraddrptr
memset(&addrptr,'\0',sizeof(addrptr));
retval=inet_aton("68.178.157.132",&addrptr);
https://www.tutorialspoint.com/cgibin/printpage.cgi
10/26
12/11/2016
UnixSocketQuickGuide
(...)
in_addr_tinet_addr(constchar*strptr)
ThisfunctioncallconvertsthespecifiedstringintheInternetstandarddotnotationtoanintegervaluesuitableforuse
asanInternetaddress.TheconvertedaddresswillbeinNetworkByteOrder(bytesorderedfromlefttoright).It
returnsa32bitbinarynetworkbyteorderedIPv4addressandINADDR_NONEonerror.
Followingistheusageexample
#include<arpa/inet.h>
(...)
structsockaddr_indest;
memset(&dest,'\0',sizeof(dest));
dest.sin_addr.s_addr=inet_addr("68.178.157.132");
(...)
char*inet_ntoa(structin_addrinaddr)
ThisfunctioncallconvertsthespecifiedInternethostaddresstoastringintheInternetstandarddotnotation.
Followingistheusageexample
#include<arpa/inet.h>
(...)
char*ip;
ip=inet_ntoa(dest.sin_addr);
printf("IPAddressis:%s\n",ip);
(...)
UnixSocketCoreFunctions
ThischapterdescribesthecoresocketfunctionsrequiredtowriteacompleteTCPclientandserver.
ThefollowingdiagramshowsthecompleteClientandServerinteraction
https://www.tutorialspoint.com/cgibin/printpage.cgi
11/26
12/11/2016
UnixSocketQuickGuide
ThesocketFunction
ToperformnetworkI/O,thefirstthingaprocessmustdois,callthesocketfunction,specifyingthetypeof
communicationprotocoldesiredandprotocolfamily,etc.
#include<sys/types.h>
#include<sys/socket.h>
intsocket(intfamily,inttype,intprotocol);
Thiscallreturnsasocketdescriptorthatyoucanuseinlatersystemcallsor1onerror.
Parameters
familyItspecifiestheprotocolfamilyandisoneoftheconstantsshownbelow
Family
Description
AF_INET IPv4protocols
AF_INET6 IPv6protocols
AF_LOCAL Unixdomainprotocols
AF_ROUTE RoutingSockets
AF_KEY
Ketsocket
ThischapterdoesnotcoverotherprotocolsexceptIPv4.
typeItspecifiesthekindofsocketyouwant.Itcantakeoneofthefollowingvalues
https://www.tutorialspoint.com/cgibin/printpage.cgi
12/26
12/11/2016
UnixSocketQuickGuide
Type
Description
SOCK_STREAM
Streamsocket
SOCK_DGRAM
Datagramsocket
SOCK_SEQPACKET Sequencedpacketsocket
SOCK_RAW
Rawsocket
protocolTheargumentshouldbesettothespecificprotocoltypegivenbelow,or0toselectthesystem'sdefaultfor
thegivencombinationoffamilyandtype
Protocol
Description
IPPROTO_TCP TCPtransportprotocol
IPPROTO_UDP UDPtransportprotocol
IPPROTO_SCTP SCTPtransportprotocol
TheconnectFunction
TheconnectfunctionisusedbyaTCPclienttoestablishaconnectionwithaTCPserver.
#include<sys/types.h>
#include<sys/socket.h>
intconnect(intsockfd,structsockaddr*serv_addr,intaddrlen);
Thiscallreturns0ifitsuccessfullyconnectstotheserver,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
serv_addrItisapointertostructsockaddrthatcontainsdestinationIPaddressandport.
addrlenSetittosizeof(structsockaddr).
ThebindFunction
Thebindfunctionassignsalocalprotocoladdresstoasocket.WiththeInternetprotocols,theprotocoladdressisthe
combinationofeithera32bitIPv4addressora128bitIPv6address,alongwitha16bitTCPorUDPportnumber.
ThisfunctioniscalledbyTCPserveronly.
#include<sys/types.h>
#include<sys/socket.h>
intbind(intsockfd,structsockaddr*my_addr,intaddrlen);
Thiscallreturns0ifitsuccessfullybindstotheaddress,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
my_addrItisapointertostructsockaddrthatcontainsthelocalIPaddressandport.
addrlenSetittosizeof(structsockaddr).
YoucanputyourIPaddressandyourportautomatically
A0valueforportnumbermeansthatthesystemwillchoosearandomport,andINADDR_ANYvalueforIPaddress
meanstheserver'sIPaddresswillbeassignedautomatically.
server.sin_port=0;
server.sin_addr.s_addr=INADDR_ANY;
https://www.tutorialspoint.com/cgibin/printpage.cgi
13/26
12/11/2016
UnixSocketQuickGuide
NOTEAllportsbelow1024arereserved.Youcansetaportabove1024andbelow65535unlesstheyaretheones
beingusedbyotherprograms.
ThelistenFunction
ThelistenfunctioniscalledonlybyaTCPserveranditperformstwoactions
Thelistenfunctionconvertsanunconnectedsocketintoapassivesocket,indicatingthatthekernelshould
acceptincomingconnectionrequestsdirectedtothissocket.
Thesecondargumenttothisfunctionspecifiesthemaximumnumberofconnectionsthekernelshouldqueue
forthissocket.
#include<sys/types.h>
#include<sys/socket.h>
intlisten(intsockfd,intbacklog);
Thiscallreturns0onsuccess,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
backlogItisthenumberofallowedconnections.
TheacceptFunction
TheacceptfunctioniscalledbyaTCPservertoreturnthenextcompletedconnectionfromthefrontofthecompleted
connectionqueue.Thesignatureofthecallisasfollows
#include<sys/types.h>
#include<sys/socket.h>
intaccept(intsockfd,structsockaddr*cliaddr,socklen_t*addrlen);
Thiscallreturnsanonnegativedescriptoronsuccess,otherwiseitreturns1onerror.Thereturneddescriptoris
assumedtobeaclientsocketdescriptorandallreadwriteoperationswillbedoneonthisdescriptortocommunicate
withtheclient.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
cliaddrItisapointertostructsockaddrthatcontainsclientIPaddressandport.
addrlenSetittosizeof(structsockaddr).
ThesendFunction
ThesendfunctionisusedtosenddataoverstreamsocketsorCONNECTEDdatagramsockets.Ifyouwanttosend
dataoverUNCONNECTEDdatagramsockets,youmustusesendto()function.
Youcanusewrite()systemcalltosenddata.Itssignatureisasfollows
intsend(intsockfd,constvoid*msg,intlen,intflags);
Thiscallreturnsthenumberofbytessentout,otherwiseitwillreturn1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
https://www.tutorialspoint.com/cgibin/printpage.cgi
14/26
12/11/2016
UnixSocketQuickGuide
msgItisapointertothedatayouwanttosend.
lenItisthelengthofthedatayouwanttosend(inbytes).
flagsItissetto0.
TherecvFunction
TherecvfunctionisusedtoreceivedataoverstreamsocketsorCONNECTEDdatagramsockets.Ifyouwantto
receivedataoverUNCONNECTEDdatagramsocketsyoumustuserecvfrom().
Youcanuseread()systemcalltoreadthedata.Thiscallisexplainedinhelperfunctionschapter.
intrecv(intsockfd,void*buf,intlen,unsignedintflags);
Thiscallreturnsthenumberofbytesreadintothebuffer,otherwiseitwillreturn1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
bufItisthebuffertoreadtheinformationinto.
lenItisthemaximumlengthofthebuffer.
flagsItissetto0.
ThesendtoFunction
ThesendtofunctionisusedtosenddataoverUNCONNECTEDdatagramsockets.Itssignatureisasfollows
intsendto(intsockfd,constvoid*msg,intlen,unsignedintflags,conststructsockaddr*to,inttolen);
Thiscallreturnsthenumberofbytessent,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
msgItisapointertothedatayouwanttosend.
lenItisthelengthofthedatayouwanttosend(inbytes).
flagsItissetto0.
toItisapointertostructsockaddrforthehostwheredatahastobesent.
tolenItissetittosizeof(structsockaddr).
TherecvfromFunction
TherecvfromfunctionisusedtoreceivedatafromUNCONNECTEDdatagramsockets.
intrecvfrom(intsockfd,void*buf,intlen,unsignedintflagsstructsockaddr*from,int*fromlen);
Thiscallreturnsthenumberofbytesreadintothebuffer,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
https://www.tutorialspoint.com/cgibin/printpage.cgi
15/26
12/11/2016
UnixSocketQuickGuide
bufItisthebuffertoreadtheinformationinto.
lenItisthemaximumlengthofthebuffer.
flagsItissetto0.
fromItisapointertostructsockaddrforthehostwheredatahastoberead.
fromlenItissetittosizeof(structsockaddr).
ThecloseFunction
Theclosefunctionisusedtoclosethecommunicationbetweentheclientandtheserver.Itssyntaxisasfollows
intclose(intsockfd);
Thiscallreturns0onsuccess,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
TheshutdownFunction
Theshutdownfunctionisusedtogracefullyclosethecommunicationbetweentheclientandtheserver.Thisfunction
givesmorecontrolincomparisontotheclosefunction.Givenbelowisthesyntaxofshutdown
intshutdown(intsockfd,inthow);
Thiscallreturns0onsuccess,otherwiseitreturns1onerror.
Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
howPutoneofthenumbers
0indicatesthatreceivingisnotallowed,
1indicatesthatsendingisnotallowed,and
2indicatesthatbothsendingandreceivingarenotallowed.Whenhowissetto2,it'sthesamethingas
close().
TheselectFunction
Theselectfunctionindicateswhichofthespecifiedfiledescriptorsisreadyforreading,readyforwriting,orhasan
errorconditionpending.
Whenanapplicationcallsrecvorrecvfrom,itisblockeduntildataarrivesforthatsocket.Anapplicationcouldbe
doingotherusefulprocessingwhiletheincomingdatastreamisempty.Anothersituationiswhenanapplication
receivesdatafrommultiplesockets.
Callingrecvorrecvfromonasocketthathasnodatainitsinputqueuepreventsimmediatereceptionofdatafrom
othersockets.Theselectfunctioncallsolvesthisproblembyallowingtheprogramtopollallthesockethandlesto
seeiftheyareavailablefornonblockingreadingandwritingoperations.
Givenbelowisthesyntaxofselect
intselect(intnfds,fd_set*readfds,fd_set*writefds,fd_set*errorfds,structtimeval*timeout);
Thiscallreturns0onsuccess,otherwiseitreturns1onerror.
https://www.tutorialspoint.com/cgibin/printpage.cgi
16/26
12/11/2016
UnixSocketQuickGuide
Parameters
nfdsItspecifiestherangeoffiledescriptorstobetested.Theselect()functiontestsfiledescriptorsinthe
rangeof0tonfds1
readfdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedforbeing
readytoread,andonoutput,indicateswhichfiledescriptorsarereadytoread.ItcanbeNULLtoindicatean
emptyset.
writefdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedfor
beingreadytowrite,andonoutput,indicateswhichfiledescriptorsarereadytowrite.ItcanbeNULLto
indicateanemptyset.
exceptfdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedfor
errorconditionspending,andonoutputindicates,whichfiledescriptorshaveerrorconditionspending.Itcan
beNULLtoindicateanemptyset.
timeoutItpointstoatimevalstructthatspecifieshowlongtheselectcallshouldpollthedescriptorsforan
availableI/Ooperation.Ifthetimeoutvalueis0,thenselectwillreturnimmediately.Ifthetimeoutargumentis
NULL,thenselectwillblockuntilatleastonefile/sockethandleisreadyforanavailableI/Ooperation.
OtherwiseselectwillreturnaftertheamountoftimeinthetimeouthaselapsedORwhenatleastone
file/socketdescriptorisreadyforanI/Ooperation.
ThereturnvaluefromselectisthenumberofhandlesspecifiedinthefiledescriptorsetsthatarereadyforI/O.Ifthe
timelimitspecifiedbythetimeoutfieldisreached,selectreturn0.Thefollowingmacrosexistformanipulatingafile
descriptorset
FD_CLR(fd,&fdset)Clearsthebitforthefiledescriptorfdinthefiledescriptorsetfdset.
FD_ISSET(fd,&fdset)Returnsanonzerovalueifthebitforthefiledescriptorfdissetinthefiledescriptor
setpointedtobyfdset,and0otherwise.
FD_SET(fd,&fdset)Setsthebitforthefiledescriptorfdinthefiledescriptorsetfdset.
FD_ZERO(&fdset)Initializesthefiledescriptorsetfdsettohavezerobitsforallfiledescriptors.
Thebehaviorofthesemacrosisundefinedifthefdargumentislessthan0orgreaterthanorequaltoFD_SETSIZE.
Example
fd_setfds;
structtimevaltv;
/*dosocketinitializationetc.
tv.tv_sec=1;
tv.tv_usec=500000;
/*tvnowrepresents1.5seconds*/
FD_ZERO(&fds);
/*addssocktothefiledescriptorset*/
FD_SET(sock,&fds);
/*wait1.5secondsforanydatatobereadfromanysinglesocket*/
select(sock+1,&fds,NULL,NULL,&tv);
if(FD_ISSET(sock,&fds)){
recvfrom(s,buffer,buffer_len,0,&sa,&sa_len);
/*dosomething*/
}
else{
/*dosomethingelse*/
}
https://www.tutorialspoint.com/cgibin/printpage.cgi
17/26
12/11/2016
UnixSocketQuickGuide
UnixSocketHelperFunctions
Thischapterdescribesallthehelperfunctions,whichareusedwhiledoingsocketprogramming.Otherhelper
functionsaredescribedinthechaptersPortsandServices,andNetworkByteOrders.
ThewriteFunction
Thewritefunctionattemptstowritenbytebytesfromthebufferpointedbybuftothefileassociatedwiththeopen
filedescriptor,fildes.
Youcanalsousesend()functiontosenddatatoanotherprocess.
#include<unistd.h>
intwrite(intfildes,constvoid*buf,intnbyte);
Uponsuccessfulcompletion,write()returnsthenumberofbytesactuallywrittentothefileassociatedwithfildes.
Thisnumberisnevergreaterthannbyte.Otherwise,1isreturned.
Parameters
fildesItisasocketdescriptorreturnedbythesocketfunction.
bufItisapointertothedatayouwanttosend.
nbyteItisthenumberofbytestobewritten.Ifnbyteis0,write()willreturn0andhavenootherresultsifthe
fileisaregularfileotherwise,theresultsareunspecified.
ThereadFunction
Thereadfunctionattemptstoreadnbytebytesfromthefileassociatedwiththeopenfiledescriptor,fildes,intothe
bufferpointedtobybuf.
Youcanalsouserecv()functiontoreaddatatoanotherprocess.
#include<unistd.h>
intread(intfildes,constvoid*buf,intnbyte);
Uponsuccessfulcompletion,write()returnsthenumberofbytesactuallywrittentothefileassociatedwithfildes.
Thisnumberisnevergreaterthannbyte.Otherwise,1isreturned.
Parameters
fildesItisasocketdescriptorreturnedbythesocketfunction.
bufItisthebuffertoreadtheinformationinto.
nbyteItisthenumberofbytestoread.
TheforkFunction
Theforkfunctioncreatesanewprocess.Thenewprocesscalledthechildprocesswillbeanexactcopyofthecalling
process(parentprocess).Thechildprocessinheritsmanyattributesfromtheparentprocess.
#include<sys/types.h>
#include<unistd.h>
intfork(void);
https://www.tutorialspoint.com/cgibin/printpage.cgi
18/26
12/11/2016
UnixSocketQuickGuide
Uponsuccessfulcompletion,fork()returns0tothechildprocessandtheprocessIDofthechildprocesstotheparent
process.Otherwise1isreturnedtotheparentprocess,nochildprocessiscreatedanderrnoissettoindicatethe
error.
Parameters
voidItmeansnoparameterisrequired.
ThebzeroFunction
Thebzerofunctionplacesnbytenullbytesinthestrings.Thisfunctionisusedtosetallthesocketstructureswith
nullvalues.
voidbzero(void*s,intnbyte);
Thisfunctiondoesnotreturnanything.
Parameters
sItspecifiesthestringwhichhastobefilledwithnullbytes.Thiswillbeapointtosocketstructurevariable.
nbyteItspecifiesthenumberofbytestobefilledwithnullvalues.Thiswillbethesizeofthesocket
structure.
ThebcmpFunction
Thebcmpfunctioncomparesbytestrings1againstbytestrings2.Bothstringsareassumedtobenbytebyteslong.
intbcmp(constvoid*s1,constvoid*s2,intnbyte);
Thisfunctionreturns0ifbothstringsareidentical,1otherwise.Thebcmp()functionalwaysreturns0whennbyteis
0.
Parameters
s1Itspecifiesthefirststringtobecompared.
s2Itspecifiesthesecondstringtobecompared.
nbyteItspecifiesthenumberofbytestobecompared.
ThebcopyFunction
Thebcopyfunctioncopiesnbytebytesfromstrings1tothestrings2.Overlappingstringsarehandledcorrectly.
voidbcopy(constvoid*s1,void*s2,intnbyte);
Thisfunctiondoesnotreturnanything.
Parameters
s1Itspecifiesthesourcestring.
s2vItspecifiesthedestinationstring.
nbyteItspecifiesthenumberofbytestobecopied.
ThememsetFunction
https://www.tutorialspoint.com/cgibin/printpage.cgi
19/26
12/11/2016
UnixSocketQuickGuide
Thememsetfunctionisalsousedtosetstructurevariablesinthesamewayasbzero.Takealookatitssyntax,given
below.
void*memset(void*s,intc,intnbyte);
Thisfunctionreturnsapointertovoidinfact,apointertothesetmemoryandyouneedtocasteitaccordingly.
Parameters
sItspecifiesthesourcetobeset.
cItspecifiesthecharactertosetonnbyteplaces.
nbyteItspecifiesthenumberofbytestobeset.
UnixSocketServerExamples
TomakeaprocessaTCPserver,youneedtofollowthestepsgivenbelow
Createasocketwiththesocket()systemcall.
Bindthesockettoanaddressusingthebind()systemcall.ForaserversocketontheInternet,anaddress
consistsofaportnumberonthehostmachine.
Listenforconnectionswiththelisten()systemcall.
Acceptaconnectionwiththeaccept()systemcall.Thiscalltypicallyblocksuntilaclientconnectswiththe
server.
Sendandreceivedatausingtheread()andwrite()systemcalls.
Nowletusputthesestepsintheformofsourcecode.Putthiscodeintothefileserver.candcompileitwithgcc
compiler.
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<string.h>
intmain(intargc,char*argv[]){
intsockfd,newsockfd,portno,clilen;
charbuffer[256];
structsockaddr_inserv_addr,cli_addr;
intn;
/*Firstcalltosocket()function*/
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){
perror("ERRORopeningsocket");
exit(1);
}
/*Initializesocketstructure*/
bzero((char*)&serv_addr,sizeof(serv_addr));
portno=5001;
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(portno);
/*Nowbindthehostaddressusingbind()call.*/
if(bind(sockfd,(structsockaddr*)&serv_addr,sizeof(serv_addr))<0){
perror("ERRORonbinding");
https://www.tutorialspoint.com/cgibin/printpage.cgi
20/26
12/11/2016
UnixSocketQuickGuide
exit(1);
}
/*Nowstartlisteningfortheclients,hereprocesswill
*goinsleepmodeandwillwaitfortheincomingconnection
*/
listen(sockfd,5);
clilen=sizeof(cli_addr);
/*Acceptactualconnectionfromtheclient*/
newsockfd=accept(sockfd,(structsockaddr*)&cli_addr,&clilen);
if(newsockfd<0){
perror("ERRORonaccept");
exit(1);
}
/*Ifconnectionisestablishedthenstartcommunicating*/
bzero(buffer,256);
n=read(newsockfd,buffer,255);
if(n<0){
perror("ERRORreadingfromsocket");
exit(1);
}
printf("Hereisthemessage:%s\n",buffer);
/*Writearesponsetotheclient*/
n=write(newsockfd,"Igotyourmessage",18);
if(n<0){
perror("ERRORwritingtosocket");
exit(1);
}
return0;
}
HandleMultipleConnections
Toallowtheservertohandlemultiplesimultaneousconnections,wemakethefollowingchangesintheabovecode
Puttheacceptstatementandthefollowingcodeinaninfiniteloop.
Afteraconnectionisestablished,callfork()tocreateanewprocess.
Thechildprocesswillclosesockfdandcalldoprocessingfunction,passingthenewsocketfiledescriptorasan
argument.Whenthetwoprocesseshavecompletedtheirconversation,asindicatedbydoprocessing()
returning,thisprocesssimplyexits.
Theparentprocessclosesnewsockfd.Asallofthiscodeisinaninfiniteloop,itwillreturntotheaccept
statementtowaitforthenextconnection.
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<string.h>
voiddoprocessing(intsock);
intmain(intargc,char*argv[]){
intsockfd,newsockfd,portno,clilen;
charbuffer[256];
structsockaddr_inserv_addr,cli_addr;
intn,pid;
https://www.tutorialspoint.com/cgibin/printpage.cgi
21/26
12/11/2016
UnixSocketQuickGuide
/*Firstcalltosocket()function*/
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){
perror("ERRORopeningsocket");
exit(1);
}
/*Initializesocketstructure*/
bzero((char*)&serv_addr,sizeof(serv_addr));
portno=5001;
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(portno);
/*Nowbindthehostaddressusingbind()call.*/
if(bind(sockfd,(structsockaddr*)&serv_addr,sizeof(serv_addr))<0){
perror("ERRORonbinding");
exit(1);
}
/*Nowstartlisteningfortheclients,here
*processwillgoinsleepmodeandwillwait
*fortheincomingconnection
*/
listen(sockfd,5);
clilen=sizeof(cli_addr);
while(1){
newsockfd=accept(sockfd,(structsockaddr*)&cli_addr,&clilen);
if(newsockfd<0){
perror("ERRORonaccept");
exit(1);
}
/*Createchildprocess*/
pid=fork();
if(pid<0){
perror("ERRORonfork");
exit(1);
}
if(pid==0){
/*Thisistheclientprocess*/
close(sockfd);
doprocessing(newsockfd);
exit(0);
}
else{
close(newsockfd);
}
}/*endofwhile*/
}
Thefollowingcodeseqmentshowsasimpleimplementationofdoprocessingfunction.
voiddoprocessing(intsock){
intn;
charbuffer[256];
bzero(buffer,256);
n=read(sock,buffer,255);
if(n<0){
perror("ERRORreadingfromsocket");
exit(1);
}
printf("Hereisthemessage:%s\n",buffer);
n=write(sock,"Igotyourmessage",18);
https://www.tutorialspoint.com/cgibin/printpage.cgi
22/26
12/11/2016
UnixSocketQuickGuide
if(n<0){
perror("ERRORwritingtosocket");
exit(1);
}
UnixSocketClientExamples
TomakeaprocessaTCPclient,youneedtofollowthestepsgivenbelow&minus
Createasocketwiththesocket()systemcall.
Connectthesockettotheaddressoftheserverusingtheconnect()systemcall.
Sendandreceivedata.Thereareanumberofwaystodothis,butthesimplestwayistousetheread()and
write()systemcalls.
Nowletusputthesestepsintheformofsourcecode.Putthiscodeintothefileclient.candcompileitwithgcc
compiler.
Runthisprogramandpasshostnameandportnumberoftheserver,toconnecttotheserver,whichyoualreadymust
haveruninanotherUnixwindow.
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<netinet/in.h>
#include<string.h>
intmain(intargc,char*argv[]){
intsockfd,portno,n;
structsockaddr_inserv_addr;
structhostent*server;
charbuffer[256];
if(argc<3){
fprintf(stderr,"usage%shostnameport\n",argv[0]);
exit(0);
}
portno=atoi(argv[2]);
/*Createasocketpoint*/
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){
perror("ERRORopeningsocket");
exit(1);
}
server=gethostbyname(argv[1]);
if(server==NULL){
fprintf(stderr,"ERROR,nosuchhost\n");
exit(0);
}
bzero((char*)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
bcopy((char*)server>h_addr,(char*)&serv_addr.sin_addr.s_addr,server>h_length);
serv_addr.sin_port=htons(portno);
/*Nowconnecttotheserver*/
if(connect(sockfd,(structsockaddr*)&serv_addr,sizeof(serv_addr))<0){
perror("ERRORconnecting");
https://www.tutorialspoint.com/cgibin/printpage.cgi
23/26
12/11/2016
UnixSocketQuickGuide
exit(1);
}
/*Nowaskforamessagefromtheuser,thismessage
*willbereadbyserver
*/
printf("Pleaseenterthemessage:");
bzero(buffer,256);
fgets(buffer,255,stdin);
/*Sendmessagetotheserver*/
n=write(sockfd,buffer,strlen(buffer));
if(n<0){
perror("ERRORwritingtosocket");
exit(1);
}
/*Nowreadserverresponse*/
bzero(buffer,256);
n=read(sockfd,buffer,255);
if(n<0){
perror("ERRORreadingfromsocket");
exit(1);
}
printf("%s\n",buffer);
return0;
}
UnixSocketSummary
Hereisalistofallthefunctionsrelatedtosocketprogramming.
PortandServiceFunctions
Unixprovidesthefollowingfunctionstofetchservicenamefromthe/etc/servicesfile.
structservent*getservbyname(char*name,char*proto)Thiscalltakesaservicenameandaprotocol
nameandreturnsthecorrespondingportnumberforthatservice.
structservent*getservbyport(intport,char*proto)Thiscalltakesaportnumberandaprotocolnameand
returnsthecorrespondingservicename.
ByteOrderingFunctions
unsignedshorthtons(unsignedshorthostshort)Thisfunctionconverts16bit(2byte)quantitiesfromhost
byteordertonetworkbyteorder.
unsignedlonghtonl(unsignedlonghostlong)Thisfunctionconverts32bit(4byte)quantitiesfromhost
byteordertonetworkbyteorder.
unsignedshortntohs(unsignedshortnetshort)Thisfunctionconverts16bit(2byte)quantitiesfrom
networkbyteordertohostbyteorder.
unsignedlongntohl(unsignedlongnetlong)Thisfunctionconverts32bitquantitiesfromnetworkbyte
ordertohostbyteorder.
IPAddressFunctions
intinet_aton(constchar*strptr,structin_addr*addrptr)Thisfunctioncallconvertsthespecifiedstring,
intheInternetstandarddotnotation,toanetworkaddress,andstorestheaddressinthestructureprovided.The
https://www.tutorialspoint.com/cgibin/printpage.cgi
24/26
12/11/2016
UnixSocketQuickGuide
convertedaddresswillbeinNetworkByteOrder(bytesorderedfromlefttoright).Itreturns1ifthestringis
validand0onerror.
in_addr_tinet_addr(constchar*strptr)Thisfunctioncallconvertsthespecifiedstring,intheInternet
standarddotnotation,toanintegervaluesuitableforuseasanInternetaddress.Theconvertedaddresswillbe
inNetworkByteOrder(bytesorderedfromlefttoright).Itreturnsa32bitbinarynetworkbyteorderedIPv4
addressandINADDR_NONEonerror.
char*inet_ntoa(structin_addrinaddr)ThisfunctioncallconvertsthespecifiedInternethostaddresstoa
stringintheInternetstandarddotnotation.
SocketCoreFunctions
intsocket(intfamily,inttype,intprotocol)Thiscallreturnsasocketdescriptorthatyoucanuseinlater
systemcallsoritgivesyou1onerror.
intconnect(intsockfd,structsockaddr*serv_addr,intaddrlen)TheconnectfunctionisusedbyaTCP
clienttoestablishaconnectionwithaTCPserver.Thiscallreturns0ifitsuccessfullyconnectstotheserver,
otherwiseitreturns1.
intbind(intsockfd,structsockaddr*my_addr,intaddrlen)Thebindfunctionassignsalocalprotocol
addresstoasocket.Thiscallreturns0ifitsuccessfullybindstotheaddress,otherwiseitreturns1.
intlisten(intsockfd,intbacklog)ThelistenfunctioniscalledonlybyaTCPservertolistenfortheclient
request.Thiscallreturns0onsuccess,otherwiseitreturns1.
intaccept(intsockfd,structsockaddr*cliaddr,socklen_t*addrlen)Theacceptfunctioniscalledbya
TCPservertoacceptclientrequestsandtoestablishactualconnection.Thiscallreturnsanonnegative
descriptoronsuccess,otherwiseitreturns1.
intsend(intsockfd,constvoid*msg,intlen,intflags)Thesendfunctionisusedtosenddataoverstream
socketsorCONNECTEDdatagramsockets.Thiscallreturnsthenumberofbytessentout,otherwiseitreturns
1.
intrecv(intsockfd,void*buf,intlen,unsignedintflags)Therecvfunctionisusedtoreceivedataover
streamsocketsorCONNECTEDdatagramsockets.Thiscallreturnsthenumberofbytesreadintothebuffer,
otherwiseitreturns1onerror.
intsendto(intsockfd,constvoid*msg,intlen,unsignedintflags,conststructsockaddr*to,inttolen)
ThesendtofunctionisusedtosenddataoverUNCONNECTEDdatagramsockets.Thiscallreturnsthenumber
ofbytessent,otherwiseitreturns1onerror.
intrecvfrom(intsockfd,void*buf,intlen,unsignedintflagsstructsockaddr*from,int*fromlen)The
recvfromfunctionisusedtoreceivedatafromUNCONNECTEDdatagramsockets.Thiscallreturnsthe
numberofbytesreadintothebuffer,otherwiseitreturns1onerror.
intclose(intsockfd)Theclosefunctionisusedtocloseacommunicationbetweentheclientandtheserver.
Thiscallreturns0onsuccess,otherwiseitreturns1.
intshutdown(intsockfd,inthow)Theshutdownfunctionisusedtogracefullycloseacommunication
betweentheclientandtheserver.Thisfunctiongivesmorecontrolincomparisontoclosefunction.Itreturns0
onsuccess,1otherwise.
intselect(intnfds,fd_set*readfds,fd_set*writefds,fd_set*errorfds,structtimeval*timeout)This
functionisusedtoreadorwritemultiplesockets.
SocketHelperFunctions
intwrite(intfildes,constvoid*buf,intnbyte)Thewritefunctionattemptstowritenbytebytesfromthe
bufferpointedtobybuftothefileassociatedwiththeopenfiledescriptor,fildes.Uponsuccessfulcompletion,
write()returnsthenumberofbytesactuallywrittentothefileassociatedwithfildes.Thisnumberisnever
greaterthannbyte.Otherwise,1isreturned.
https://www.tutorialspoint.com/cgibin/printpage.cgi
25/26
12/11/2016
UnixSocketQuickGuide
intread(intfildes,constvoid*buf,intnbyte)Thereadfunctionattemptstoreadnbytebytesfromthefile
associatedwiththeopenfiledescriptor,fildes,intothebufferpointedtobybuf.Uponsuccessfulcompletion,
write()returnsthenumberofbytesactuallywrittentothefileassociatedwithfildes.Thisnumberisnever
greaterthannbyte.Otherwise,1isreturned.
intfork(void)Theforkfunctioncreatesanewprocess.Thenewprocess,calledthechildprocess,willbean
exactcopyofthecallingprocess(parentprocess).
voidbzero(void*s,intnbyte)Thebzerofunctionplacesnbytenullbytesinthestrings.Thisfunctionwill
beusedtosetallthesocketstructureswithnullvalues.
intbcmp(constvoid*s1,constvoid*s2,intnbyte)Thebcmpfunctioncomparesthebytestrings1against
thebytestrings2.Boththestringsareassumedtobenbytebyteslong.
voidbcopy(constvoid*s1,void*s2,intnbyte)Thebcopyfunctioncopiesnbytebytesfromthestrings1to
thestrings2.Overlappingstringsarehandledcorrectly.
void*memset(void*s,intc,intnbyte)Thememsetfunctionisalsousedtosetstructurevariablesinthe
samewayasbzero.
https://www.tutorialspoint.com/cgibin/printpage.cgi
26/26