Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 16.4 Connection Establishment 605


•The port number in the address cannot be less than 1,024 unless the process has
the appropriate privilege (i.e., is the superuser).
•Usually,only one socket endpoint can be bound to a given address, although
some protocols allow duplicate bindings.

For the Internet domain, if we specify the special IP addressINADDR_ANY(defined in
<netinet/in.h>), the socket endpoint will be bound to all the system’s network
interfaces. This means that we can receive packets from any of the network interface
cards installed in the system.We’ll see in the next section that the system will choose an
address and bind it to our socket for us if we callconnectorlistenwithout first
binding an address to the socket.
We can use thegetsocknamefunction to discover the address bound to a socket.
#include <sys/socket.h>
int getsockname(intsockfd,struct sockaddr *restrictaddr,
socklen_t *restrictalenp);
Returns: 0 if OK,−1 on error
Beforecallinggetsockname, we setalenpto point to an integer containing the size of
thesockaddrbuffer.Onreturn, the integer is set to the size of the address returned. If
the address won’t fit in the buffer provided, the address is silently truncated. If no
address is currently bound to the socket, the results areundefined.
If the socket is connected to a peer, we can find out the peer’s address by calling the
getpeernamefunction.
#include <sys/socket.h>
int getpeername(intsockfd,struct sockaddr *restrictaddr,
socklen_t *restrictalenp);
Returns: 0 if OK,−1 on error
Other than returning the peer’s address, thegetpeernamefunction is identical to the
getsocknamefunction.

16.4 Connection Establishment


If we’redealing with a connection-oriented network service (SOCK_STREAM or
SOCK_SEQPACKET), then before we can exchange data, we need to create a connection
between the socket of the process requesting the service (the client) and the process
providing the service (the server).We use theconnectfunction to create a connection.
#include <sys/socket.h>
int connect(intsockfd,const struct sockaddr *addr,socklen_tlen);
Returns: 0 if OK,−1 on error
Free download pdf