Perl Socket Programming
Socket, also known as "Socket" (socket), is typically used by applications to send requests over a network or respond to network requests, enabling communication between hosts or processes on a single computer.
In this chapter, we will introduce how to use Socket services in the Perl language.
* * *
### Creating a Server
* Use the **socket** function to create a socket service.
* Use the **bind** function to bind a port.
* Use the **listen** function to listen on the port.
* Use the **accept** function to accept client requests.
### Creating a Client
* Use the **socket** function to create a socket service.
* Use the **connect** function to connect to the socket server.
The following diagram illustrates the communication flow between the client and server:
!(#)
* * *
## Server Socket Functions
### socket Function
In Perl, we use the socket() function to create a socket. The syntax is as follows:
socket( SOCKET, DOMAIN, TYPE, PROTOCOL );
Parameter analysis:
* **DOMAIN** specifies the protocol family for the created socket. For example:
* `AF_INET` represents IPv4 network protocol
* `AF_INET6` represents IPv6
* `AF_UNIX` represents local sockets (using a file)
* **TYPE** specifies the socket type, which can be SOCK_STREAM for connection-oriented or SOCK_DGRAM for connectionless communication.
* **PROTOCOL** should be **(getprotobyname('tcp'))**. It specifies the actual transport protocol to be used.
Therefore, the socket function call is as follows:
use Socket # Defines PF_INET and SOCK_STREAM socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp')));
### bind() Function
Use bind() to assign an address to a socket:
bind( SOCKET, ADDRESS );
SOCKET is a socket descriptor. ADDRESS is the socket address (TCP/IP) containing three elements:
* Address family (TCP/IP uses AF_INET, which might be 2 on your system)
* Port number (e.g., 21)
* Network address (e.g., 10.12.12.168)
After creating a socket with socket(), only the protocol is assigned, not an address. Before accepting connections from other hosts, you must call bind() to assign an address to the socket.
A simple example is as follows:
use Socket # Defines PF_INET and SOCK_STREAM $port = 12345; # Port to listen on $server_ip_address = "10.12.12.168"; bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Cannot bind port! n";
**or die** executes if binding the address fails.
By setting the setsockopt() option SO_REUSEADDR, the port can be reused immediately.
The **pack_sockaddr_in()** function converts the address to binary format.
### listen() Function
After a socket is bound to an address, the listen() function starts listening for possible connection requests. However, this can only be used when reliable data streams are guaranteed:
listen( SOCKET, QUEUESIZE );
SOCKET: A socket descriptor.
QUEUESIZE: An integer that determines the size of the listening queue. When a connection request arrives, it enters this queue; when a connection request is accepted by accept(), it is removed from the queue; when the queue is full, new connection requests return an error.
Once a connection is accepted, 0 is returned for success, and -1 for an error.
### accept() Function
The accept() function accepts a requested socket connection. If successful, it returns the compressed network address; otherwise, it returns FALSE:
accept( NEW_SOCKET, SOCKET );
NEW_SOCKET: A socket descriptor.
SOCKET: A socket descriptor.
accept() is typically used in an infinite loop:
while(1) { accept( NEW_SOCKET, SOCKT ); .......}
The above example can listen for client requests in real-time.
* * *
## Client Functions
### connect() Function
The connect() system call sets up a connection for a socket, with parameters including the file descriptor and host address.
connect( SOCKET, ADDRESS );
The following example creates a connection to a server socket:
$port = 21; # FTP port $server_ip_address = "10.12.12.168"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Cannot bind port! n";
* * *
## Complete Example
Next, let's understand the application of all socket functions through a complete example:
Server server.pl code:
## Example
#!/usr/bin/perl -w use strict; use Socket; my$port = shift || 7890; my$proto = getprotobyname('tcp'); my$server = "localhost"; socket(SOCKET, PF_INET, SOCK_STREAM, $proto)or die"Cannot open socket $!n"; setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)or die"Cannot set SO_REUSEADDR $!n"; bind(SOCKET, pack_sockaddr_in($port, inet_aton($server)))or die"Cannot bind port $port! n"; listen(SOCKET, 5)or die"listen: $!"; print"Server started: $portn"; my$client_addr; while($client_addr = accept(NEW_SOCKET, SOCKET)){my$name = gethostbyaddr($client_addr, AF_INET); print NEW_SOCKET"I am a message from the server"; print"Connection received from $namen"; close NEW_SOCKET; }
Open a terminal and execute the following code:
$ perl server.pl Server started: 7890
Client client.pl code:
## Example
#!/usr/bin/perl -w use strict; use Socket; my$host = shift || 'localhost'; my$port = shift || 7890; my$server = "localhost"; socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp')))or die"Cannot create socket $!n"; connect(SOCKET, pack_sockaddr_in($port, inet_aton($server)))or die"Cannot connect: port $port! n"; my$line; while($line = ){print"$linen"; }close SOCKET or die"close: $!";
Open another terminal and execute the following code:
$ perl client.pl I am a message from the server
YouTip