Perl Socket programming

Socket is also known as a socket, and applications typically make or respond to network requests through "sockets" that allow communication between hosts or processes on a computer.

In this section, we'll show you how to use the Socket service in the Perl language.


Create a service side

  • Use the socket function to create the socket service.

  • Use the bind function to bind the port.

  • Use the listen function to listen to the port.

  • Use the accept function to receive client requests.

Create a client

  • Use the socket function to create the socket service.

  • Connect to the socket server using the connect function.

The following diagram illustrates the communication flow between the client and the service side:

Perl Socket programming


The service-side socket function

The socket function

In Perl, we use the socket() function to create sockets in the following syntax format:

socket( SOCKET, DOMAIN, TYPE, PROTOCOL );

Parameter resolution:

  • The socket created by domain specifies the protocol set. For example:

    • AF_INET the IPv4 network protocol
    • AF_INET6 IPv6
    • AF_UNIX represents a local socket (using a file)

  • Type socket types can be divided into different types of connections or connections depending on whether SOCK_STREAM or SOCK_DGRAM

  • PROTOCOL should be (getprotobyname ('tcp')). S pecify the transport protocol that is actually in use.

So the socket function is called as follows:

use Socket     # 定义了 PF_INET 和 SOCK_STREAM

socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]);

Bind() function

Use bind() to assign an address to the socket:

bind( SOCKET, ADDRESS );

SOCKET A socket descriptor. Address is an socket address (TCP/IP) that contains three elements:

  • Address cluster (TCP/IP, is AF_INET, may be 2 on your system)

  • Port number (e.g. 21)

  • Network address (e.g. 10.12.12.168)

When you create a socket using socket(), only the protocol it uses is granted, and no address is assigned. Before accepting a connection from another host, bind() must be called to assign an address to the socket.

A simple example is as follows:

use Socket        # 定义了 PF_INET 和 SOCK_STREAM

$port = 12345;    # 监听的端口
$server_ip_address = "10.12.12.168";
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
   or die "无法绑定端口! \n";

or die is executed after the binding address fails.

By setting setsockopt() you have the option SO_REUSEADDR the settings port can be reused immediately.

pack_sockaddr_in () function converts the address to a binary format.

Listen() function

When the socket is bound to an address, the listen() function starts listening for possible connection requests. However, this can only be used when there is a reliable data flow guarantee:

listen( SOCKET, QUEUESIZE );

SOCKET : A descriptor for a socket.

QUEUESIZE : is an integer that determines the size of the listening queue, which enters when a connection request arrives, moves out of the listening queue when a connection request is accepted by accept(), and returns an error when the queue is full.

Once the connection is accepted, returning 0 indicates success and error returning -1.

Accept() function

The accept() function accepts the requested socket connection. I f successful, return the network address in compressed form, otherwise return FALSE:

accept( NEW_SOCKET, SOCKET );

SOCKET : A descriptor for a socket.

ADDRESS: ADDRESS is an socket address (TCP/IP) that contains three elements:

  • Address cluster (TCP/IP, is AF_INET, may be 2 on your system)

  • Port number (e.g. 21)

  • Network address (e.g. 10.12.12.168)

accept() is usually used in infinite loops:

while(1) {
   accept( NEW_SOCKET, SOCKT );
   .......
}

The above instances can listen to client requests in real time.


The client function

Connect() function

The connect() system calls to set the connection for a socket with a file descriptor and host address.

connect( SOCKET, ADDRESS );

Here's an instance that connects to the service-side socket:

$port = 21;    #  ftp 端口
$server_ip_address = "10.12.12.168";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))
    or die "无法绑定端口! \n";

The full instance

Let's take a full example of how all socket functions are applied:

Service-side server.pl code:

#!/usr/bin/perl -w
# Filename : server.pl

use strict;
use Socket;

# 使用端口 7890 作为默认值
my $port = shift || 7890;
my $proto = getprotobyname('tcp');
my $server = "localhost";  # 设置本地地址

# 创建 socket, 端口可重复使用,创建多个连接
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
   or die "无法打开 socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
   or die "无法设置 SO_REUSEADDR $!\n";

# 绑定端口并监听
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "无法绑定端口 $port! \n";

listen(SOCKET, 5) or die "listen: $!";
print "访问启动:$port\n";

# 接收请求
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
   # send them a message, close connection
   my $name = gethostbyaddr($client_addr, AF_INET );
   print NEW_SOCKET "我是来自服务端的信息";
   print "Connection recieved from $name\n";
   close NEW_SOCKET;
}

Open a terminal and execute the following code:

$ perl sever.pl
访问启动:7890

The client.pl code:

#!/usr/bin/perl -w
# Filename : client.pl

use strict;
use Socket;

# 初始化地址与端口
my $host = shift || 'localhost';
my $port = shift || 7890;
my $server = "localhost";  # 主机地址

# 创建 socket 并连接
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
   or die "无法创建 socket $!\n";
connect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "无法连接:port $port! \n";

my $line;
while ($line = <SOCKET>) {
        print "$line\n";
}
close SOCKET or die "close: $!";

Open another terminal and execute the following code:

$ perl client.pl
我是来自服务端的信息