我寫了一個網絡課的小程序,遇到了一些困惑。IO ::套接字與套接字我「使用」兩者?
我目前正在使用的東西,但在我發現的perl網絡示例中看到了一些不一致之處。
有的人導入Socket模塊,有的導入IO :: Socket模塊。更令人困惑的是,一些導入Socket和IO :: Socket。
有沒有重點?我以爲IO :: Socket會導入Socket?
我問,因爲我試圖使用一個函數「getaddrinfo()」,它不停地大喊我的「未定義的子程序& main :: getaddrinfo調用./tcp_server.pl行13」。它在Socket perldoc中。
我通過手動指定主機IP來得到它,但我希望它自動檢索運行它的機器的主機IP。有什麼建議?
這裏是我的代碼:
#!/usr/bin/perl
# Flushing to STDOUT after each write
$| = 1;
use warnings;
use strict;
use Socket;
use IO::Socket::INET;
# Server side information
# Works with IPv4 addresses on the same domain
my ($err, @res) = getaddrinfo(`hostname`); #'128.101.38.191';
my $listen_port = '7070';
my $protocal = 'tcp';
my ($socket, $client_socket);
my ($client_address, $client_port);
# Data initializer
my $data = undef;
# Creating interface
$socket = IO::Socket::INET->new (
LocalHost => shift @res,
LocalPort => $listen_port,
Proto => $protocal,
Listen => 5,
Reuse => 1,
) or die "Socket could not be created, failed with error: $!\n"; # Prints error code
print "Socket created using host: @res \n";
print "Waiting for client connection on port $listen_port\n";
while(1) {
# Infinite loop to accept a new connection
$client_socket = $socket->accept()
or die "accept error code: $!\n";
# Retrieve client information
$client_address = $client_socket->peerhost();
$client_port = $client_socket->peerport();
print "Client accepted: $client_address, $client_port\n";
# Write
$data = "Data from Server";
print $client_socket "$data\n";
# Read
$data = <$client_socket>;
print "Received from client: $data\n";
}
$socket->close();
爲什麼使用'getaddrinfo'?只需將主機名傳遞給'LocalHost' – ikegami
我想獲取IP地址。當我使用實際的主機名時,我似乎無法使其工作。 – rusty
你忘記刪除尾隨換行符了嗎? – ikegami