Perl LWP无法连接到Windows 11上的localhost

yftpprvb  于 2022-11-15  发布在  Perl
关注(0)|答案(1)|浏览(189)

我正在写一个小的Perl脚本来测试本地开发环境中的API。我在Windows11上使用Strawberry Perl。应用程序是在ASP.NETMVC中。
当我运行它时,我得到以下错误:

500 Can't connect to localhost:44311 (Bad file descriptor)

到目前为止,我编写的完整代码如下:

#!/usr/bin/perl
use warnings;
use v5.20;
use LWP;
use LWP::UserAgent;

use IO::Socket::IP;                                             # needed for "AF_INET"
@LWP::Protocol::http::EXTRA_SOCK_OPTS = ( Family => AF_INET );
@LWP::Protocol::https::EXTRA_SOCK_OPTS = ( Family => AF_INET );  # force IPv4 (doesn't seem to work)

use JSON;

# check socket is open
use IO::Socket::INET;
my @hosts = qw/ localhost:44311 /;
foreach my $host ( @hosts ) {
    my $open = defined IO::Socket::INET->new(PeerAddr => $host, Timeout => 5) || 0;
    printf "Probed %s -> %s \n", $host, $open ? 'ok' : 'NOK';
}
## end check, it is!

my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");

my %get_details = (
    email => 'MY_EMAIL',
   password => 'PasswordOfMine'
);

# Create a request
my $req = HTTP::Request->new(POST => 'https://localhost:44311/api/token');
$req->content_type('application/json');
$req->content( encode_json (\%get_details) );

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

if ($res->is_success) {
    print $res->content;
}
else {
    print $res->status_line, "\n";
}

正如您所看到的,我从其他地方获得的套接字探测器报告Perl可以访问套接字。

IPv6协议

我知道这可能是一个IPv6问题,因为LWP默认将localhost解析为IPv6地址,而我的应用程序仅在IPv4上运行。
我不能简单地将“localhost”切换为127.0.0.1,因为应用程序只接受具有正确主机名的请求。如果我在Web浏览器中打开127.0.0.1,我会得到:

Bad Request - Invalid Hostname

所以很不幸这不是解决办法。
有没有直接的方法来设置LWP解析'localhost'为IPv4只?这将是最受欢迎的,因为我宁愿使用我的选择脚本语言来发挥周围的API。

k0pti3hp

k0pti3hp1#

这修复了它:

$ua->ssl_opts(verify_hostname => 0);

原来这是因为localhost使用了一个自生成的证书,我所要做的就是关闭SSL验证。
因此,它与IPv6没有任何关系,所以我不需要在开始时与套接字发生任何混乱。
恐慌结束了,谢谢!

相关问题