What is socket programming in Perl?
Socket
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
Port is the number associated with a socket. It is used to identify the application within the host.
Client-server applications
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:
Socket functionalities
1. socket() is used to create a new socket. Its syntax is given below:
socket( SOCKET, DOMAIN, TYPE, PROTOCOL );
DOMAINis the protocol family, which is set toPF_INET.TYPEis the type of socket. We will set it toSOCK_STREAMfor TCP/IP connection.PROTOCOLis 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)
SOCKETis the socket object returned by thesocket()call.ADDRESSis the socket address consisting of port number and IP.
3. listen() is used to listen for requests on the specified port.
listen( SOCKET, QUEUESIZE );
SOCKETis the socket object returned by thesocket()call.QUEUESIZEis 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_SOCKETis the socket object returned if the connection is accepted. It is used for all future communication between the client and server.SOCKETis the socket object returned by thesocket()call.
5. connect() is used to connect the socket to an address. The client uses it to connect to the server.
connect( SOCKET, ADDRESS)
SOCKETis the socket object returned by thesocket()call.ADDRESSis the socket address consisting of port number and IP.
Example
!/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
Free Resources