0% found this document useful (0 votes)
38 views26 pages

TutorialsPoint - Unix Socket Quick Guide

Unix Socket Quick Guide

Uploaded by

paolocollector
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views26 pages

TutorialsPoint - Unix Socket Quick Guide

Unix Socket Quick Guide

Uploaded by

paolocollector
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

12/11/2016

UnixSocketQuickGuide

UnixSocketQuickGuide
[Link]
[Link]

WhatisaSocket?
[Link]
precise,it'[Link],everyI/Oactionisdoneby
[Link]
networkconnection,atextfile,aterminal,orsomethingelse.
Toaprogrammer,[Link]
read()andwrite()workwithsocketsinthesamewaytheydowithfilesandpipes.
[Link]
featureisnowavailablewithmostcurrentUNIXsystemreleases.

WhereisSocketUsed?
[Link]
[Link],SMTP,andPOP3makeuseofsocketsto
establishconnectionbetweenclientandserverandthenforexchangingdata.

SocketTypes
[Link]
rarelyused.
Processesarepresumedtocommunicateonlybetweensocketsofthesametypebutthereisnorestrictionthat
preventscommunicationbetweensocketsofdifferenttypes.
[Link]
threeitems"A,B,C",theywillarriveinthesameorder"A,B,C".ThesesocketsuseTCP(Transmission
ControlProtocol)[Link],[Link]
recordsdonothaveanyboundaries.
[Link]'reconnectionlessbecause
youdon'tneedtohaveanopenconnectionasinStreamSocketsyoubuildapacketwiththedestination
[Link](UserDatagramProtocol).
RawSocketsTheseprovideusersaccesstotheunderlyingcommunicationprotocols,whichsupportsocket
[Link],thoughtheirexactcharacteristicsaredependenton
[Link]
providedmainlyforthoseinterestedindevelopingnewcommunicationprotocols,orforgainingaccesstosome
ofthemorecrypticfacilitiesofanexistingprotocol.
SequencedPacketSocketsTheyaresimilartoastreamsocket,withtheexceptionthatrecordboundariesare
[Link](NS)socketabstraction,andisvery
[Link]
SequencePacketProtocol(SPP)orInternetDatagramProtocol(IDP)headersonapacketoragroupof
packets,eitherbywritingaprototypeheaderalongwithwhateverdataistobesent,orbyspecifyingadefault
headertobeusedwithalloutgoingdata,andallowstheusertoreceivetheheadersonincomingpackets.

WhatisNext?
[Link]

1/26

12/11/2016

UnixSocketQuickGuide

ThenextfewchaptersaremeanttostrengthenyourbasicsandprepareafoundationbeforeyoucanwriteServerand
[Link],thenyou
[Link]
fewchapterstomakeyourbasebeforemovingontodoprogramming.

UnixSocketNetworkAddresses
Beforeweproceedwiththeactualstuff,letusdiscussabitabouttheNetworkAddressestheIPAddress.
TheIPhostaddress,ormorecommonlyjustIPaddress,[Link]
forInternetProtocolandreferstotheInternetLayeroftheoverallnetworkarchitectureoftheInternet.
[Link]
participatingusernetwork,thehostonthenetwork,andtheclassoftheusernetwork.
AnIPaddressisusuallywritteninadotteddecimalnotationoftheformN1.N2.N3.N4,whereeachNiisadecimal
numberbetween0and255decimal(00throughFFhexadecimal).

AddressClasses
IPaddressesaremanagedandcreatedbytheInternetAssignedNumbersAuthority(IANA).Therearefivedifferent
[Link].
ClassAaddressesbeginwith0xxx,or1to126decimal.
ClassBaddressesbeginwith10xx,or128to191decimal.
ClassCaddressesbeginwith110x,or192to223decimal.
ClassDaddressesbeginwith1110,or224to239decimal.
ClassEaddressesbeginwith1111,or240to254decimal.
Addressesbeginningwith01111111,or127decimal,arereservedforloopbackandforinternaltestingonalocal
machine[Youcantestthis:youshouldalwaysbeabletoping127.0.0.1,whichpointstoyourself]ClassDaddresses
[Link]
addresses.

Example
Class Leftmostbits Startaddress Finishaddress
A
0xxx
[Link]
[Link]
B
10xx
[Link]
[Link]
C
110x
[Link]
[Link]
D
1110
[Link]
[Link]
E
1111
[Link]
[Link]

Subnetting
[Link]
networkinanorganization,useofdifferentphysicalmedia(suchasEthernet,FDDI,WAN,etc.),preservationof
addressspace,[Link].
ThebasicideainsubnettingistopartitionthehostidentifierportionoftheIPaddressintotwoparts
Asubnetaddresswithinthenetworkaddressitselfand
Ahostaddressonthesubnet.

[Link]

2/26

12/11/2016

UnixSocketQuickGuide

Forexample,acommonClassBaddressformatisN1.N2.S.H,whereN1.N2identifiestheClassBnetwork,the8bit
Sfieldidentifiesthesubnet,andthe8bitHfieldidentifiesthehostonthesubnet.

UnixSocketNetworkHostNames
Hostnamesintermsofnumbersaredifficulttorememberandhencetheyaretermedbyordinarynamessuchas
[Link].
TheprocessoffindingoutdottedIPaddressbasedonthegivenalphanumerichostnameisknownashostname
resolution.
[Link]
DomainNameSystems(DNS),whichkeepthemappingofIPaddressesandthecorrespondingordinarynames.

The/etc/hostsFile
[Link],
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
[Link]
[Link]
[Link]
[Link]

[Link]
addresstohostnameandviceversa.
Youwouldnothaveaccesstoeditthisfile,soifyouwanttoputanyhostnamealongwithIPaddress,thenyouwould
needtohaverootpermission.

UnixSocketClientServerModel
MostoftheNetApplicationsusetheClientServerarchitecture,whichreferstotwoprocessesortwoapplications
[Link],
andanotherprocessactsasaserver.

ClientProcess
Thisistheprocess,[Link],thisprocessmay
terminateormaydosomeotherprocessing.
Example,InternetBrowserworksasaclientapplication,whichsendsarequesttotheWebServertogetoneHTML
webpage.

ServerProcess
[Link],thisprocesswill
performtherequiredprocessing,gathertherequestedinformation,[Link],it
[Link].
ExampleWebServerkeepswaitingforrequestsfromInternetBrowsersandassoonasitgetsanyrequestfroma
browser,itpicksuparequestedHTMLpageandsendsitbacktothatBrowser.
[Link]

3/26

12/11/2016

UnixSocketQuickGuide

Notethattheclientneedstoknowtheaddressoftheserver,buttheserverdoesnotneedtoknowtheaddressoreven
[Link],bothsidescan
sendandreceiveinformation.

2tierand3tierarchitectures
Therearetwotypesofclientserverarchitectures
2tierarchitectureInthisarchitecture,[Link]
[Link]
[Link](SSL).
3tierarchitecturesInthisarchitecture,[Link]
[Link]
[Link]
requiredauthentication,[Link]
[Link]
youwanttoimplementa3tierarchitecture,thenyoucankeepanymiddlewarelikeWebLogicorWebSphere
softwareinbetweenyourWebServerandWebBrowser.

TypesofServer
Therearetwotypesofserversyoucanhave
IterativeServerThisisthesimplestformofserverwhereaserverprocessservesoneclientandafter
completingthefirstrequest,[Link],anotherclientkeepswaiting.
ConcurrentServersThistypeofserverrunsmultipleconcurrentprocessestoservemanyrequestsatatime
[Link]
concurrentserverunderUnixistoforkachildprocesstohandleeachclientseparately.

HowtoMakeClient
Thesystemcallsforestablishingaconnectionaresomewhatdifferentfortheclientandtheserver,butbothinvolve
[Link].
Thestepsinvolvedinestablishingasocketontheclientsideareasfollows
Createasocketwiththesocket()systemcall.
Connectthesockettotheaddressoftheserverusingtheconnect()systemcall.
[Link],butthesimplestwayistousetheread()and
write()systemcalls.

HowtomakeaServer
Thestepsinvolvedinestablishingasocketontheserversideareasfollows
Createasocketwiththesocket()systemcall.
Bindthesockettoanaddressusingthebind()[Link],anaddress
consistsofaportnumberonthehostmachine.
Listenforconnectionswiththelisten()systemcall.
Acceptaconnectionwiththeaccept()[Link]
connectswiththeserver.
Sendandreceivedatausingtheread()andwrite()systemcalls.
[Link]

4/26

12/11/2016

UnixSocketQuickGuide

ClientandServerInteraction
FollowingisthediagramshowingthecompleteClientandServerinteraction

UnixSocketStructures
VariousstructuresareusedinUnixSocketProgrammingtoholdinformationabouttheaddressandport,andother
[Link]
inthischapterarerelatedtoInternetProtocolFamily.

sockaddr
Thefirststructureissockaddrthatholdsthesocketinformation
structsockaddr{
unsignedshortsa_family;
charsa_data[14];
};

Thisisagenericsocketaddressstructure,[Link]
tableprovidesadescriptionofthememberfields
Attribute

Values

Description

AF_INET
[Link]

5/26

12/11/2016

UnixSocketQuickGuide

AF_UNIX
sa_family

AF_NS

[Link],weuse
AF_INET.

AF_IMPLINK
sa_data

Protocol
specific
Address

Thecontentofthe14bytesofprotocolspecificaddressareinterpretedaccordingtothe
[Link],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

[Link],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

[Link]

6/26

12/11/2016

UnixSocketQuickGuide

#defineh_addrh_addr_list[0]
};

Hereisthedescriptionofthememberfields
Attribute

Values
Description
[Link]
h_name
[Link],[Link],[Link],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
[Link],SMTP,FTPPOP3,etc.
s_aliases ALIAS [Link].
s_port
80
[Link],forHTTP,thiswillbe80.
s_proto

TCP
UDP

[Link].

TipsonSocketStructures
[Link],fillthemin,andpass
[Link]
functionanditfillsinthecontents.
Wealwayspassthesestructuresbyreference(i.e.,wepassapointertothestructure,notthestructureitself),andwe
alwayspassthesizeofthestructureasanotherargument.
Whenasocketfunctionfillsinastructure,thelengthisalsopassedbyreference,sothatitsvaluecanbeupdatedby
[Link].
Always,setthestructurevariablestoNULL(i.e.,'\0')byusingmemset()forbzero()functions,otherwiseitmayget
unexpectedjunkvaluesinyourstructure.

UnixSocketPortsandServices
Whenaclientprocesswantstoaconnectaserver,theclientmusthaveawayofidentifyingtheserverthatitwantsto
connect.Iftheclientknowsthe32bitInternetaddressofthehostonwhichtheserverresides,itcancontactthathost.
[Link]

7/26

12/11/2016

UnixSocketQuickGuide

Buthowdoestheclientidentifytheparticularserverprocessrunningonthathost?
Toresolvetheproblemofidentifyingaparticularserverprocessrunningonahost,bothTCPandUDPhavedefineda
groupofwellknownports.
Forourpurpose,[Link]
numberssmallerthan1024areconsideredwellknownforexample,telnetusesport23,httpuses80,ftpuses21,
andsoon.
Theportassignmentstonetworkservicescanbefoundinthefile/etc/[Link]
[Link]
anyotherserver.
[Link]
[Link],YahooMessengerrunson5050,SIPServerruns
on5060,etc.

ExamplePortsandServices
[Link]
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
[Link]

8/26

12/11/2016

UnixSocketQuickGuide

Attribute Values
Description
s_name http
[Link],SMTP,FTPPOP3,etc.
s_aliases ALIAS [Link],itwillbesettoNULL.
s_port
80
[Link],forHTTP,itwillbe80.
s_proto

TCP
UDP

[Link].

UnixSocketNetworkByteOrders
Unfortunately,notallcomputersstorethebytesthatcompriseamultibytevalueinthesameorder.Considera16bit
[Link].
LittleEndianInthisscheme,loworderbyteisstoredonthestartingaddress(A)andhighorderbyteis
storedonthenextaddress(A+1).
BigEndianInthisscheme,highorderbyteisstoredonthestartingaddress(A)andloworderbyteisstored
onthenextaddress(A+1).
Toallowmachineswithdifferentbyteorderconventionscommunicatewitheachother,theInternetprotocolsspecify
[Link].
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.
[Link]
endianmachines,[Link],nocodeis
insertedsincenoneisneededthefunctionsaredefinedasnull.

ProgramtoDetermineHostByteOrder
[Link].
[Link]

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
$>./[Link]
littleendian
$>

UnixSocketIPAddressFunctions
[Link]
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
[Link](bytesorderedfromleft
toright).Itreturns1ifthestringwasvalidand0onerror.
Followingistheusageexample
#include<arpa/inet.h>
(...)
intretval;
structin_addraddrptr

memset(&addrptr,'\0',sizeof(addrptr));
retval=inet_aton("[Link]",&addrptr);
[Link]

10/26

12/11/2016

UnixSocketQuickGuide

(...)

in_addr_tinet_addr(constchar*strptr)
ThisfunctioncallconvertsthespecifiedstringintheInternetstandarddotnotationtoanintegervaluesuitableforuse
[Link](bytesorderedfromlefttoright).It
returnsa32bitbinarynetworkbyteorderedIPv4addressandINADDR_NONEonerror.
Followingistheusageexample
#include<arpa/inet.h>
(...)
structsockaddr_indest;
memset(&dest,'\0',sizeof(dest));
dest.sin_addr.s_addr=inet_addr("[Link]");

(...)

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

[Link]

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.
[Link]
[Link]

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
[Link],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;
[Link]

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
[Link]
#include<sys/types.h>
#include<sys/socket.h>
intaccept(intsockfd,structsockaddr*cliaddr,socklen_t*addrlen);

Thiscallreturnsanonnegativedescriptoronsuccess,[Link]
assumedtobeaclientsocketdescriptorandallreadwriteoperationswillbedoneonthisdescriptortocommunicate
withtheclient.

Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
cliaddrItisapointertostructsockaddrthatcontainsclientIPaddressandport.
addrlenSetittosizeof(structsockaddr).

ThesendFunction
[Link]
dataoverUNCONNECTEDdatagramsockets,youmustusesendto()function.
Youcanusewrite()[Link]
intsend(intsockfd,constvoid*msg,intlen,intflags);

Thiscallreturnsthenumberofbytessentout,otherwiseitwillreturn1onerror.

Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
[Link]

14/26

12/11/2016

UnixSocketQuickGuide

msgItisapointertothedatayouwanttosend.
lenItisthelengthofthedatayouwanttosend(inbytes).
flagsItissetto0.

TherecvFunction
[Link]
receivedataoverUNCONNECTEDdatagramsocketsyoumustuserecvfrom().
Youcanuseread()[Link].
intrecv(intsockfd,void*buf,intlen,unsignedintflags);

Thiscallreturnsthenumberofbytesreadintothebuffer,otherwiseitwillreturn1onerror.

Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
bufItisthebuffertoreadtheinformationinto.
lenItisthemaximumlengthofthebuffer.
flagsItissetto0.

ThesendtoFunction
[Link]
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.

[Link]

15/26

12/11/2016

UnixSocketQuickGuide

bufItisthebuffertoreadtheinformationinto.
lenItisthemaximumlengthofthebuffer.
flagsItissetto0.
fromItisapointertostructsockaddrforthehostwheredatahastoberead.
fromlenItissetittosizeof(structsockaddr).

ThecloseFunction
[Link]
intclose(intsockfd);

Thiscallreturns0onsuccess,otherwiseitreturns1onerror.

Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.

TheshutdownFunction
[Link]
[Link]
intshutdown(intsockfd,inthow);

Thiscallreturns0onsuccess,otherwiseitreturns1onerror.

Parameters
sockfdItisasocketdescriptorreturnedbythesocketfunction.
howPutoneofthenumbers
0indicatesthatreceivingisnotallowed,
1indicatesthatsendingisnotallowed,and
2indicatesthatbothsendingandreceivingarenotallowed.Whenhowissetto2,it'sthesamethingas
close().

TheselectFunction
Theselectfunctionindicateswhichofthespecifiedfiledescriptorsisreadyforreading,readyforwriting,orhasan
errorconditionpending.
Whenanapplicationcallsrecvorrecvfrom,[Link]
[Link]
receivesdatafrommultiplesockets.
Callingrecvorrecvfromonasocketthathasnodatainitsinputqueuepreventsimmediatereceptionofdatafrom
[Link]
seeiftheyareavailablefornonblockingreadingandwritingoperations.
Givenbelowisthesyntaxofselect
intselect(intnfds,fd_set*readfds,fd_set*writefds,fd_set*errorfds,structtimeval*timeout);

Thiscallreturns0onsuccess,otherwiseitreturns1onerror.
[Link]

16/26

12/11/2016

UnixSocketQuickGuide

Parameters
[Link]()functiontestsfiledescriptorsinthe
rangeof0tonfds1
readfdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedforbeing
readytoread,andonoutput,[Link]
emptyset.
writefdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedfor
beingreadytowrite,andonoutput,[Link]
indicateanemptyset.
exceptfdsItpointstoanobjectoftypefd_setthatoninput,specifiesthefiledescriptorstobecheckedfor
errorconditionspending,andonoutputindicates,[Link]
beNULLtoindicateanemptyset.
timeoutItpointstoatimevalstructthatspecifieshowlongtheselectcallshouldpollthedescriptorsforan
availableI/Ooperation.Ifthetimeoutvalueis0,[Link]
NULL,thenselectwillblockuntilatleastonefile/sockethandleisreadyforanavailableI/Ooperation.
OtherwiseselectwillreturnaftertheamountoftimeinthetimeouthaselapsedORwhenatleastone
file/socketdescriptorisreadyforanI/Ooperation.
ThereturnvaluefromselectisthenumberofhandlesspecifiedinthefiledescriptorsetsthatarereadyforI/[Link]
timelimitspecifiedbythetimeoutfieldisreached,[Link]
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*/
}

[Link]

17/26

12/11/2016

UnixSocketQuickGuide

UnixSocketHelperFunctions
Thischapterdescribesallthehelperfunctions,[Link]
functionsaredescribedinthechaptersPortsandServices,andNetworkByteOrders.

ThewriteFunction
Thewritefunctionattemptstowritenbytebytesfromthebufferpointedbybuftothefileassociatedwiththeopen
filedescriptor,fildes.
Youcanalsousesend()functiontosenddatatoanotherprocess.
#include<unistd.h>
intwrite(intfildes,constvoid*buf,intnbyte);

Uponsuccessfulcompletion,write()returnsthenumberofbytesactuallywrittentothefileassociatedwithfildes.
[Link],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.
[Link],1isreturned.

Parameters
fildesItisasocketdescriptorreturnedbythesocketfunction.
bufItisthebuffertoreadtheinformationinto.
nbyteItisthenumberofbytestoread.

TheforkFunction
[Link]
process(parentprocess).Thechildprocessinheritsmanyattributesfromtheparentprocess.
#include<sys/types.h>
#include<unistd.h>
intfork(void);

[Link]

18/26

12/11/2016

UnixSocketQuickGuide

Uponsuccessfulcompletion,fork()returns0tothechildprocessandtheprocessIDofthechildprocesstotheparent
process.Otherwise1isreturnedtotheparentprocess,nochildprocessiscreatedanderrnoissettoindicatethe
error.

Parameters
voidItmeansnoparameterisrequired.

ThebzeroFunction
[Link]
nullvalues.
voidbzero(void*s,intnbyte);

Thisfunctiondoesnotreturnanything.

Parameters
[Link].
[Link]
structure.

ThebcmpFunction
[Link].
intbcmp(constvoid*s1,constvoid*s2,intnbyte);

Thisfunctionreturns0ifbothstringsareidentical,[Link]()functionalwaysreturns0whennbyteis
0.

Parameters
s1Itspecifiesthefirststringtobecompared.
s2Itspecifiesthesecondstringtobecompared.
nbyteItspecifiesthenumberofbytestobecompared.

ThebcopyFunction
[Link].
voidbcopy(constvoid*s1,void*s2,intnbyte);

Thisfunctiondoesnotreturnanything.

Parameters
s1Itspecifiesthesourcestring.
s2vItspecifiesthedestinationstring.
nbyteItspecifiesthenumberofbytestobecopied.

ThememsetFunction
[Link]

19/26

12/11/2016

UnixSocketQuickGuide

[Link],given
below.
void*memset(void*s,intc,intnbyte);

Thisfunctionreturnsapointertovoidinfact,apointertothesetmemoryandyouneedtocasteitaccordingly.

Parameters
sItspecifiesthesourcetobeset.
cItspecifiesthecharactertosetonnbyteplaces.
nbyteItspecifiesthenumberofbytestobeset.

UnixSocketServerExamples
TomakeaprocessaTCPserver,youneedtofollowthestepsgivenbelow
Createasocketwiththesocket()systemcall.
Bindthesockettoanaddressusingthebind()[Link],anaddress
consistsofaportnumberonthehostmachine.
Listenforconnectionswiththelisten()systemcall.
Acceptaconnectionwiththeaccept()[Link]
server.
Sendandreceivedatausingtheread()andwrite()systemcalls.
[Link]
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");
[Link]

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
[Link],asindicatedbydoprocessing()
returning,thisprocesssimplyexits.
[Link],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;

[Link]

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);
[Link]

22/26

12/11/2016

UnixSocketQuickGuide

if(n<0){
perror("ERRORwritingtosocket");
exit(1);
}

UnixSocketClientExamples
TomakeaprocessaTCPclient,youneedtofollowthestepsgivenbelow&minus
Createasocketwiththesocket()systemcall.
Connectthesockettotheaddressoftheserverusingtheconnect()systemcall.
[Link],butthesimplestwayistousetheread()and
write()systemcalls.
[Link]
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");
[Link]

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,[Link]
[Link]

24/26

12/11/2016

UnixSocketQuickGuide

convertedaddresswillbeinNetworkByteOrder(bytesorderedfromlefttoright).Itreturns1ifthestringis
validand0onerror.
in_addr_tinet_addr(constchar*strptr)Thisfunctioncallconvertsthespecifiedstring,intheInternet
standarddotnotation,[Link]
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
[Link]
descriptoronsuccess,otherwiseitreturns1.
intsend(intsockfd,constvoid*msg,intlen,intflags)Thesendfunctionisusedtosenddataoverstream
[Link],otherwiseitreturns
1.
intrecv(intsockfd,void*buf,intlen,unsignedintflags)Therecvfunctionisusedtoreceivedataover
[Link],
otherwiseitreturns1onerror.
intsendto(intsockfd,constvoid*msg,intlen,unsignedintflags,conststructsockaddr*to,inttolen)
[Link]
ofbytessent,otherwiseitreturns1onerror.
intrecvfrom(intsockfd,void*buf,intlen,unsignedintflagsstructsockaddr*from,int*fromlen)The
[Link]
numberofbytesreadintothebuffer,otherwiseitreturns1onerror.
intclose(intsockfd)Theclosefunctionisusedtocloseacommunicationbetweentheclientandtheserver.
Thiscallreturns0onsuccess,otherwiseitreturns1.
intshutdown(intsockfd,inthow)Theshutdownfunctionisusedtogracefullycloseacommunication
[Link].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,[Link],
write()[Link]
[Link],1isreturned.
[Link]

25/26

12/11/2016

UnixSocketQuickGuide

intread(intfildes,constvoid*buf,intnbyte)Thereadfunctionattemptstoreadnbytebytesfromthefile
associatedwiththeopenfiledescriptor,fildes,[Link],
write()[Link]
[Link],1isreturned.
intfork(void)[Link],calledthechildprocess,willbean
exactcopyofthecallingprocess(parentprocess).
voidbzero(void*s,intnbyte)[Link]
beusedtosetallthesocketstructureswithnullvalues.
intbcmp(constvoid*s1,constvoid*s2,intnbyte)Thebcmpfunctioncomparesthebytestrings1against
[Link].
voidbcopy(constvoid*s1,void*s2,intnbyte)Thebcopyfunctioncopiesnbytebytesfromthestrings1to
[Link].
void*memset(void*s,intc,intnbyte)Thememsetfunctionisalsousedtosetstructurevariablesinthe
samewayasbzero.

[Link]

26/26

You might also like