Copyright © tutorialspoint.com

Socket Core Functions

previous next


Advertisements

This tutorial describes the core socket functions required to write a complete TCP client and server.

Following is the diagram showing complete Client and Server interaction:

Socket Client Server

The socket Function:

To perform network I/O, the first thing a process must do is call the socket function, specifying the type of communication protocol desired and protocol family etc.

#include <sys/types.h>
#include <sys/socket.h>

int socket (int family, int type, int protocol);

This call gives you a socket descriptor that you can use in later system calls or it gives you -1 on error.

Parameters:

family: specifies the protocol family and is one of the constants shown below:

FamilyDescription
AF_INETIPv4 protocols
AF_INET6IPv6 protocols
AF_LOCALUnix domain protocols
AF_ROUTERouting Sockets
AF_KEYKet socket

This tutorial does not talk about other protocols except IPv4.

type: specifies kind of socket you want. It can take one of the following values:

TypeDescription
SOCK_STREAMStream socket
SOCK_DGRAMDatagram socket
SOCK_SEQPACKETSequenced packet socket
SOCK_RAWRaw socket

protocol: argument should be set to the specific protocol type given below or 0 to select the system's default for the given combination of family and type:

ProtocolDescription
IPPROTO_TCPTCP transport protocol
IPPROTO_UDPUDP transport protocol
IPPROTO_SCTPSCTP transport protocol

The connect Function:

The connect function is used by a TCP client to establish a connection with a TCP server.

#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);

This call returns 0 if it successfully connects to the server otherwise it gives you -1 on error.

Parameters:

The bind Function:

The bind function assigns a local protocol address to a socket. With the Internet protocols, the protocol address is the combination of either a 32-bit IPv4 address or a 128-bit IPv6 address, along with a 16-bit TCP or UDP port number. This function is called by TCP server only.

#include <sys/types.h>
#include <sys/socket.h>

int bind(int sockfd, struct sockaddr *my_addr,int addrlen);

This call returns 0 if it successfully binds to the address otherwise it gives you -1 on error.

Parameters:

You can put your IP address and your port automatically:

A 0 value for port number means system will choose a random port and INADDR_ANY value for IP address means server's IP address will be assigned automatically.

server.sin_port = 0;  		     
server.sin_addr.s_addr = INADDR_ANY;

NOTE: As descript in Ports and Services tutorials, all ports bellow 1024 are reserved. So you can set a port above 1024 and bellow 65535 unless the ones being used by other programs.

The listen Function:

The listen function is called only by a TCP server and it performs two actions:

#include <sys/types.h>
#include <sys/socket.h>

int listen(int sockfd,int backlog);

This call returns 0 on success otherwise it gives you -1 on error.

Parameters:

The accept Function:

The accept function is called by a TCP server to return the next completed connection from the front of the completed connection queue. Following is the signature of the call:

#include <sys/types.h>
#include <sys/socket.h>

int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);

This call returns non negative descriptor on success otherwise it gives you -1 on error. The returned decriptor is assumed to be a client socket descriptor and all read write operations will be done on this descripton to communicate with the client.

Parameters:

The send Function:

The send function is used to send data over stream sockets or CONNECTED datagram sockets. If you want to send data over UNCONNECTED datagram sockets you must use sendto() function.

You can use write() system call to send the data. This call is explained in helper functions tutorial.

int send(int sockfd, const void *msg, int len, int flags);

This call returns the number of bytes sent out otherwise it will return -1 on error.

Parameters:

The recv Function:

The recv function is used to receive data over stream sockets or CONNECTED datagram sockets. If you want to receive data over UNCONNECTED datagram sockets you must use recvfrom().

You can use read() system call to read the data. This call is explained in helper functions tutorial.

int recv(int sockfd, void *buf, int len, unsigned int flags);

This call returns the number of bytes read into the buffer otherwise it will return -1 on error.

Parameters:

The sendto Function:

The sendto function is used to send data over UNCONNECTED datagram sockets. Put simply, when you use scoket type as SOCK_DGRAM

int sendto(int sockfd, const void *msg, int len, unsigned int flags,
		   const struct sockaddr *to, int tolen);

This call returns the number of bytes sent otherwise it will return -1 on error.

Parameters:

The recvfrom Function:

The recvfrom function is used to receive data from UNCONNECTED datagram sockets. Put simply, when you use scoket type as SOCK_DGRAM

int recvfrom(int sockfd, void *buf, int len, unsigned int flags
		     struct sockaddr *from, int *fromlen);

This call returns the number of bytes read into the buffer otherwise it will return -1 on error.

Parameters:

The close Function:

The close function is used to close the communication between client and server.

int close( int sockfd );

This call returns 0 on success otherwise it will return -1 on error.

Parameters:

The shutdown Function:

The shutdown function is used to gracefully close the communication between client and server. This function gives more control in caomparision of close function.

int shutdown(int sockfd, int how);

This call returns 0 on success otherwise it will return -1 on error.

Parameters:

The select Function:

The select function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.

When an application calls recv or recvfrom it is blocked until data arrives for that socket. An application could be doing other useful processing while the incoming data stream is empty. Another situation is when an application receives data from multiple sockets.

Calling recv or recvfrom on a socket that has no data in it's input queue prevents immediate reception of data from other sockets. The select function call solves this problem by allowing the program to poll all the socket handles to see if they are available for non-blocking reading and writing operations.

 int select(int  nfds,  fd_set  *readfds,  fd_set  *writefds,
     fd_set *errorfds, struct timeval *timeout);

This call returns 0 on success otherwise it will return -1 on error.

Parameters:

The return value from select is the number of handles specified in the file descriptor sets that are ready for I/O. If the time limit specified by the timeout field is reached, select return 0. The following macros exist for manipulating a file descriptor set:

The behavior of these macros is undefined if the fd argument is less than 0 or greater than or equal to FD_SETSIZE.

Example:


fd_set fds;

struct timeval tv;

/* do socket initialization etc.

tv.tv_sec = 1;
tv.tv_usec = 500000;

/* tv now represents 1.5 seconds */
 
FD_ZERO(&fds);

/* adds sock to the file descriptor set */
FD_SET(sock, &fds); 

/* wait 1.5 seconds for any data to be read 
   from any single socket */

select(sock+1, &fds, NULL, NULL, &tv);
if (FD_ISSET(sock, &fds))
{
   recvfrom(s, buffer, buffer_len, 0, &sa, &sa_len);
   /* do something */
}
else
{
   /* do something else */
}

previous next

Copyright © tutorialspoint.com