Socket is a network component that allows communication between two processes through an Operating System (OS) mechanism that connects processes to the network stack. Every computer system on a network has a unique IP address and a port number of the network application to communicate with another host. So, a socket is a combination of the port and IP address to send and receive data on the network.
Port is the number associated with a socket. It is used to identify the application within the host.
To illustrate the use of sockets, we will be creating a simple client-server application in Perl.
The server will create a socket, bind the socket to a port, listen and accept connections on the socket.
The client will create a socket and connect with the server.
The diagram below illustrates the order of functions performed by the server and client:
1. socket()
is used to create a new socket. Its syntax is given below:
socket( SOCKET, DOMAIN, TYPE, PROTOCOL );
DOMAIN
is the protocol family, which is set to PF_INET
.TYPE
is the type of socket. We will set it to SOCK_STREAM
for TCP/IP connection.PROTOCOL
is set to (getprotobyname('tcp'))[2]
. It refers to the communication protocol, which is TCP.2. bind()
is used to bind a socket with a port number.
bind( SOCKET, ADDRESS)
SOCKET
is the socket object returned by the socket()
call.ADDRESS
is the socket address consisting of port number and IP.3. listen()
is used to listen for requests on the specified port.
listen( SOCKET, QUEUESIZE );
SOCKET
is the socket object returned by the socket()
call.QUEUESIZE
is the maximum number of connection requests that the server can cater to simultaneously.4. accept
is used to request the access
function to accept incoming requests.
accept( NEW_SOCKET, SOCKET);
NEW_SOCKET
is the socket object returned if the connection is accepted. It is used for all future communication between the client and server.SOCKET
is the socket object returned by the socket()
call.5. connect()
is used to connect the socket to an address. The client uses it to connect to the server.
connect( SOCKET, ADDRESS)
SOCKET
is the socket object returned by the socket()
call.ADDRESS
is the socket address consisting of port number and IP.!/usr/bin/perl -w # Filename : client.pl use strict; use Socket; # initialize host and port my $host = shift || 'localhost'; my $port = shift || 7890; my $server = "localhost"; # Host IP running the server # create the socket, connect to the port socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]) or die "Can't create a socket $!\n"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server))) or die "Can't connect to port $port! \n"; my $line; while ($line = <SOCKET>) { print "$line\n"; } close SOCKET or die "close: $!";
Image credits: Technology vector created by stories - www.freepik.com