Perl socket programming


Socket is also called "socket". Applications usually send requests to the network or respond to network requests through "socket", so that hosts or processes on a computer can communicate.

In this chapter we will learn how to use Socket service in Perl language.


Create the server

  • Use the socket function to create the socket service.

  • Use the bind function to bind the port.

  • Use the listen function to listen on the port.

  • Use the accept function to receive client requests.

Create client

  • Use the socket function to create a socket service.

  • Use the connect function to connect to the socket server.

The following chart demonstrates the communication process between the client and the server:


Server socket function

socket function

In Perl, we use the socket() function to create a socket. The syntax format is as follows:

socket( SOCKET, DOMAIN, TYPE, PROTOCOL );

Parameter analysis:

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


    • ##AF_INET represents the IPv4 network protocol

    • AF_INET6 means IPv6

    • AF_UNIX means local socket (using a file)

  • TYPE The socket type can be divided into SOCK_STREAM or SOCK_DGRAM depending on whether it is connection-oriented or non-connection

  • PROTOCOL should be (getprotobyname('tcp'))[2]. Specifies the actual transport protocol used.

So the socket function call method is 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 the socket address (TCP/IP), which contains three elements:

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

  • Port number (for example, 21)

  • Network address (for example, 10.12.12.168)

Create using socket() After a socket is created, only the protocol it uses is assigned, and no address is assigned. Before accepting connections from other hosts, 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 Executed after failure to bind the address.

Set the port for immediate reuse by setting the setsockopt() option SO_REUSEADDR.

pack_sockaddr_in() Function converts the address into binary format.

listen() function

After the socket is bound to an address, the listen() function will start to listen for possible connection requests. However, this can only be used when reliable data flow is guaranteed:

listen( SOCKET, QUEUESIZE );

SOCKET: A socket descriptor.

QUEUESIZE: is an integer that determines the size of the listening queue. When a connection request arrives, it will enter the listening queue; when a connection request is accepted by accept(), it will be removed from the listening queue; when the queue After it is full, new connection requests will return an error.

Once the connection is accepted, return 0 for success and -1 for error.

accept() function

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

accept( NEW_SOCKET, SOCKET );

SOCKET: A socket descriptor.

ADDRESS: ADDRESS is the socket address (TCP/IP), which contains three elements:

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

  • Port number (for example 21)

  • Network address (for example 10.12.12.168)

accept() is usually used in infinite loops:

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

The above examples can monitor client requests in real time.


Client function

connect() Function

connect() system call sets the connection for a socket. The parameters include file descriptor and host address.

connect( SOCKET, ADDRESS );

The following creates an instance connected to the server 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";

Complete example

Next we use a complete example to understand all socket functions Application:

Server 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

Client 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
我是来自服务端的信息