IO::Socket::INET->new return undefined on error 吗?

Does IO::Socket::INET->new return undefined on error?

我有以下代码(更大脚本的一部分)

my $lsn = IO::Socket::INET->new(Listen => 1, LocalPort => 0); # just use any available port.
$port = $lsn->sockport();

我收到错误 Can't call method "sockport" on an undefined value

IO::Socket::INET的文档对这个问题没有说太多:https://perldoc.perl.org/IO/Socket/INET.html(有没有更好的地方可以看?对这个模块不太熟悉)

奇怪的是我最近更改了它,在它传入一个非零的、随机生成的端口号之前,有时会在端口被使用时中断。

我在本地 windows 机器上测试了 0 的传递(同样,文档似乎没有提到如何让它选择要绑定的端口),这似乎使其成为 'choose any available port',这正是我想要的,但也许它在 Solaris 上的行为有所不同(这是发生此问题的地方)?

IO::Socket::INET->new 像大多数 Perl 构造函数一样工作:成功时它 returns 是 class 的一个实例,错误时它是 false 值。有一些旁路可以获取错误原因。故意没有记录那个错误值的确切含义,重要的是它是错误的。

这导致了一般模式 my $obj = Class->new or die $reason;。在 IO::Socket 的情况下,您会从 $@ 中得到错误(非常严重)。

my $port = 999;
my $lsn = IO::Socket::INET->new(Listen => 1, LocalPort => $port)
    or die "Couldn't listen on port $port: $@";

# Couldnt listen on port 999: Permission denied at -e line 1.

I tested passing in 0 on my local windows machine(again, the documentation doesn't seem to mention how to get it to choose the port to bind), and that seemed to make it 'choose any available port', which is what I wanted, but maybe it behaves differently on Solaris (which is where this problem occurred)?

是的,这是特定于实现的。 IO::Socket::INET 只是围绕使用 bind 的套接字库的一个薄层。如果您传递 bind 端口 0,它将为您找到一个端口。这通常适用于所有现代实现。

Windows bind...

For TCP/IP, if the port is specified as zero, the service provider assigns a unique port to the application from the dynamic client port range. On Windows Vista and later, the dynamic client port range is a value between 49152 and 65535. This is a change from Windows Server 2003 and earlier where the dynamic client port range was a value between 1025 and 5000.

它是否试图绑定到特权端口(在 Solaris 上小于 1024)?如果是这样,则可能是权限问题,需要 root 访问权限才能绑定。