COMPUTERNETWORKS
UNIT-III
SocketProgramming:
Socket Address:
Asocket is oneendpoint ofa two-waycommunicationlinkbetween two programs runningon the
network.
A socket isboundtoa portnumber sothat theTCPlayer canidentifytheapplication that data is
destined to be sent to.
An endpoint is a combination of an IP address and a port number. Every TCP connection can
be uniquely identified by its two endpoints. That way you can have multiple connections
between your host and the server.
TCP/IP creates thesocketaddressas an identifier that is unique throughout all Internet
networks. TCP/IP concatenates the Internet address of the local host interface with the port
number to devise the Internet socket address.
Twotypesof(TCP/IP)sockets :
Streamsockets(e.g.usesTCP):providereliablebyte-stream service
Datagramsockets(e.g.usesUDP):providebest-effortdatagramservice,messagesupto
65.500 bytes
Sockets–Procedures:
Client-ServerCommunication–Unix:
ElementarySocketSystemCalls:
socket
TodonetworkI/O,thefirstthingaprocessmust doistocallthe socket systemcall,specifyingthe type of
communication protocol desired.
#include <sys/types.h>
#include <sys/socket.h>
intsocket(intfamily,inttype,intprotocol);
Thefamilyisone of
AF_UNIX --Unixinternalprotocols
AF_INET --Internetprotocols
AF_NS --XeroxNSProtocols
AF_IMPLINK -- IMP link layer
TheAF_prefixstandsfor"addressfamily."
The socket type is one of the following:
SOCK_STREAM stream socket
SOCK_DGRAM datagramsocket
SOCK_RAW raw socket
SOCK_SEQPACKET sequenced packet socket
SOCK_RDM reliablydeliveredmessagesocket(not
implementedyet)
Theprotocolargumenttothesocketsystemcallistypicallysetto0formostuserapplications.The valid
combinations are shown as follows.
family type protocol Actualprotocol
AF_INET SOCK_DGRAM IPPROTO_UDP UDP
AF_INET SOCK_STREAM IPPROTO_TCP TCP
AF_INET SOCK_RAW IPPROTO_ICMP ICMP
AF_INET SOCK_RAW IPPROTO_RAW (raw)
bind
Thebindsystemcallassignsanametoanunnamedsocket.
#include <sys/types.h>
#include <sys/socket.h>
intbind(intsockfd,structsockaddr*myaddr,intaddrlen);
Thefirstargumentisthesocketdescriptorreturnedfromsocketsystemcall.
Thesecondargumentisapointertoaprotocol-specificaddress.
Thirdargumentisthesizeofthisaddress.
Therearethreeusesofbind.
1. Servers register their well-known address with the system. It tells the system "this is my
address and any messages received for this address are to be given to me." Both connection-
oriented and connectionless servers need to do this before accepting client requests.
2. Aclientcanregisteraspecificaddressforitself.
3. Aconnectionless client needs to assure that the systemassigns it some uniqueaddress, so that
the other end (the server) has a valid return address to send its responses to. This corresponds
to making certain an envelope has a valid return address, if we expect to get a reply from the
person we sent the letter to.
Connect
Aclientprocessconnectsasocketdescriptorfollowingthe socketsystemcalltoestablisha connection with
a server.
#include <sys/types.h>
#include <sys/socket.h>
intconnect(intsockfd,structsockaddr*servaddr,intaddrlen);
Thesockfdisasocketdescriptorthatwasreturnedbythe socketsystemcall.
Thesecondandthirdargumentsareapointertoasocketaddress,anditssize,asdescribed earlier.
Formostconnection-orientedprotocols(TCP,forexample),theconnectsystemcallresultsin the
actual establishment of a connection between the local system and the foreign system.
Theconnectsystemcalldoesnotreturnuntiltheconnectionisestablished,oranerroris returned
to the process.
Theclientdoesnot havetobindalocaladdressbeforecallingconnect.Theconnection
typically causes these four elements of the association 5-tuple to be assigned: local-
addr, local-process, foreign-addr, and foreign-process.
Inalltheconnection-orientedclients,wewillletconnectassignthelocaladdress.
listen
Thissystemcallisusedbyaconnection-orientedserver toindicatethat itiswillingtoreceive connections.
#include <sys/types.h>
#include <sys/socket.h>
intlisten(intsockfd,intbacklog);
Itisusuallyexecutedafterboththesocketandbindsystemcalls,andimmediatelybefore the
accept system call.
Thebacklogargumentspecifieshowmanyconnectionrequestscanbequeuedbythesystem while it
waits for the server to execute the accept system call.
Thisargumentisusuallyspecifiedas5,themaximumvaluecurrentlyallowed.
accept
After a connection-oriented server executes the listen system call described above, an actual
connectionfromsomeclientprocessiswaitedforbyhavingtheserver executetheacceptsystemcall.
#include <sys/types.h>
#include <sys/socket.h>
intaccept(intsockfd,structsockaddr*peer,int*addrlen);
accept takes the first connection request on the queue and creates another socket with the same
propertiesassockfd.Iftherearenoconnectionrequestspending,thiscallblocksthecalleruntilone arrives.
The peer and addrlen arguments are used to return the address of the connected peer process (the
client). addrlen is called a value-result argument: the caller sets its value before the system call, and
thesystemcallstoresaresultinthevariable.Forthissystemcall thecallersets addrlentothesizeof the
sockaddr structure whose address is passed as the peer argument.
send,sendto,recvand recvfrom
Thesesystemcallsaresimilartothestandard readandwritesystemcalls,butadditionalarguments are
required.
#include <sys/types.h>
#include <sys/socket.h>
intsend(intsockfd,char*buff,intnbytes,intflags);
intsendto(intsockfd,char*buff,intnbytes,intflags,struct sockaddr
*to, int addrlen);
intrecv(intsockfd,char*buff,intnbytes,intflags);
intrecvfrom(intsockfd,char*buff,intnbytes,intflags,struct sockaddr
*from, int *addrlen);
Thefirstthreearguments, sockfd,buff,andnbytes,tothefoursystemcallsaresimilartothefirstthree
arguments for read and write. The flags argument can be safely set to zero ignoring the details for it.
The to argument for sendto specifies the protocol-specific address of where the data is to be sent.
Sincethisaddressisprotocol-specific,itslengthmustbespecifiedbyaddrlen.Therecvfrom system call fills
in the protocol-specific address of who sent the data into from. The length of this address is
alsoreturnedtothecallerin addrlen.Notethatthefinalargumentto sendtoisanintegervalue,while the final
argument to recvfrom is a pointer to an integer value.
close
ThenormalUnixclosesystemcall isalsousedtocloseasocket.
intclose(intfd);
If the socket beingclosedis associated witha protocolthat promises reliable delivery(e.g., TCP or SPP),
the system must assure that any data within the kernel that still has to be transmitted or
acknowledged,issent.Normally,thesystemreturnsfromthe closeimmediately,but thekernelstill tries to
send any data already queued.
AdvancedSocketSystemCalls:
1) readvandwritevsystemcalls:
Thesetwofunctionsaresimilarto read andwrite,butreadvandwritevletusreadintoor write
from one or more buffers with a single function call. These operations are
calledscatterread(sincetheinputdataisscatteredintomultipleapplicationbuffers) and
gather write (since multiple buffers are gathered for a single output operation).
#include<sys/uio.h>
intreadv(intfd,structioveciov[],intiovcount);
intwritev(intfd,structioveciov[],intiovcount);
Thesetwosystemcallsusethefollowingstructurethatisdefinedin <syst/uio.h>:
struct iovec{
caddr_tiov_base;/*stratingaddressofbuffer*/ int
iov_len;/*size of buffer in size*/
Thewritevsystemcallwritethebuffersspecifiedbyiov[0],iov[1],through
iov[iovcount-1].
Thereadvsytemcalldoestheinputequivalent.Italwaysfillsonebuffer(asspecifiedbutthe
iov_lenvalue)beforeproceedingtothenextbufferintheiovarray.
Bothsystemcallsreturnthetotalnumberofbytesreadand written.
2) getpeername-get thenameofthepeer socket
#include<sys/socket.h>
intgetpeername(intsocket,structsockaddr*address, socklen_t
*address_len);
The getpeername() function retrieves the peer address of the specified socket, stores
this address in the sockaddr structure pointed to by the address argument, and stores
the length of this address in the object pointed to by the address_len argument.
Iftheactuallengthoftheaddressisgreaterthanthelengthofthesuppliedsockaddr
structure,thestored addresswill betruncated.
If the protocol permits connections by unbound clients, and the peer is not bound,then
the value stored in the object pointed to by address is unspecified.
3) getsockname-getthesocketname
#include<sys/socket.h>
intgetsockname(intsocket,structsockaddr*address,
socklen_t *address_len);
The getsockname() function retrieves the locally-bound name of the specified socket,
stores this address in the sockaddr structure pointed to by the address argument, and
stores the length of this address in the object pointed to by the address_len argument.
Iftheactuallengthofthe addressisgreaterthanthelengthofthesuppliedsockaddr
structure,thestored addresswill betruncated.
Ifthesockethasnotbeenboundtoalocalname,thevaluestoredintheobjectpointed to by
address is unspecified.
4) getsockoptandsetsockoptallowsocketoptionsvaluestobe queriedandset,
respectively.
intgetsockopt(sockid,level,optName,optVal,optLen);
sockid:integer,socket descriptor
level:integer,thelayers oftheprotocolstack(socket,TCP,IP)
optName:integer,option
optVal:pointerto abuffer; upon returnit contains thevalue ofthespecified option
optLen:integer,in-outparameteritreturns -1if anerror occured
intsetsockopt(sockid,level,optName,optVal,optLen);
optLenis nowonlyan inputparameter
5) shutdownsystemcall:thissystemcallterminatesthenetworkconnectandprovide more
control on the full-duplex connection.
intshutdown(intsockfd,inthowto);
i. ifhowtoargumentis0: nomoredata canbereceivedon the
socket.
ii. ifhowtoargumentis1: nomoreoutput tobe allowed on the
socket.
iii. ifhowtoargumentis2: bothsend and receivetobedisallowed
shutdownallowseitherdirectionstobeclosedindependentoftheother direction.
6.)select():
7.)
RESERVEDPORTS:
Therearetwo waysforaprocesstohaveaninternetport assignedtoa socket.
a) The process can requestfor a specific port. Thisis typically for servers that need
toassign a well-known port to a socket.
b) Theprocesscanletthesystemautomaticallyassigna port.
4.3BSDprovidesalibraryfunctionthatassignsa reservedTCP streamsockettoits caller:
intrresvport(int*aport);
Internet XNS
reservedports 1-1023 1-2999
portsautomaticallyassignedbt system 1024-5000 3000-65535
portsassigned byrresvport 512-1023 -