Perl套接字中的未知主机名

时间:2019-05-10 19:25:17

标签: perl

我已经编写了一个示例perl套接字代码。客户端和服务器都在同一台计算机上运行。在接受客户端连接的服务器代码中,它将客户端主机名显示为“ anates”。我不知道从哪里选这个名字。由于我没有在任何地方设置此名称。

Server.pl

my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
   # send them a message, close connection
   print("CCCCLLLII : $client_addr\n");
   my($port2, $iaddr) = sockaddr_in($client_addr);
   print("$port2\n");
   print("$iaddr\n");
   $iaddr = inet_ntoa($iaddr);
   print("$iaddr\n");

   my $name = gethostbyaddr($client_addr, AF_INET );
   print NEW_SOCKET "Smile from the server";
   print "Connection recieved from $name\n";
   close NEW_SOCKET;
}

Client.pl

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: $!";

输出:

$ perl server.pl 
SERVER started on port 7890
CCCCLLLII : &#x2;�r&#x1;
48498
&#x1;
127.0.0.1
Connection recieved from anantes-158-1-218-114.w2-0.abo.wanadoo.fr

$ cat /etc/hosts
127.0.0.1   localhost
127.0.1.1   kaushik-Inspiron-5547

$ hostname
kaushik-Inspiron-5547

代码从哪里获得,我却没有得到。

我期望它将主机名打印为kaushik-Inspiron-5547

1 个答案:

答案 0 :(得分:2)

gethostbyaddr($client_addr, AF_INET)

应该是

gethostbyaddr($iaddr, AF_INET)

您传递给gethostbyaddr的垃圾被视为2.0.189.114,对该地址的反向DNS查找将得到anantes-158-1-218-114.w2-0.abo.wanadoo.fr


$ perl -MSocket -e'
   my $client_addr = sockaddr_in(48498, inet_aton("127.0.0.1"));
   my ($port, $iaddr) = sockaddr_in($client_addr);
   CORE::say "".gethostbyaddr($client_addr, AF_INET);  # XXX Garbage
   CORE::say "".gethostbyaddr($iaddr, AF_INET);
'
anantes-158-1-218-114.w2-0.abo.wanadoo.fr
localhost