Perl 主机到 IP 解析 [英] Perl Host to Ip Resolution

查看:39
本文介绍了Perl 主机到 IP 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将主机名解析为 IP 地址,使用 Socket 和以下内容都可以:

I am wanting to resolve a host name to an ip address which is all fine using Socket with the following:

$ip = gethostbyname($host) or die "Can't resolve ip for $host.\n";
$ip = inet_ntoa(inet_aton($host));

这可以正常工作,直到遇到不再解析为 IP 的主机名并且代码停止.如何让我的脚本继续处理要解析的主机名的其余 ip.理想情况下,我只需将 $ip 变量设置为等于 "".

This works fine until it hits a host name that no longer resolves to an IP and the code just stops. How can I get my script to continue processing the remainder ip the host names to be resolved. Ideally I would simply set the $ip variable to equal "".

即使没有 die 命令,我也尝试过,但代码在无法将名称解析为 ip 时仍然停止.

I have tried even without the die command and the code still stops when it cannot resolve the name to ip.

推荐答案

gethostbyname 的超时时间非常非常长.我假设您在看到它只需要很长时间之前就杀死了该程序.看来您确实需要更短的超时时间.

The timeout on gethostbyname is very, very long. I assume that you kill the program before you can see that it is just taking a long time. It seems that you really need a shorter timeout.

您可以使用闹钟设置自己的计时器.当它关闭时,一个 SIGALRM 信号被传递给进程,默认情况下它将终止它.因此,我们为发出 die 的信号设置了一个处理程序,从而将其转换为异常.这是 eval-ed,我们重新获得控制权.

You can set up your own timer using alarm. When it goes off a SIGALRM signal is delivered to the process, which would terminate it by default. So we set up a handler for that signal in which a die is issued, thus turning it into an exception. This is eval-ed and we get the control back.

eval {
    local $SIG{ALRM} = sub { die "Timed out" };

    alarm 5;  # or what you find most suitable

    # your code that may need a timeout

    alarm 0;
};
if ($@ and $@ !~ /Timed out/) { die }  # re-raise if it was something else

if ($@ and $@ =~ /Timed out/) {  # test
    print "We timed out\n";
}

如果您的代码在不到 5 秒内完成,我们将进入 alarm 0; 取消前一个警报,程序继续.否则 SIGALRM 被发射,但被处理并制成一个 die ,它是 eval-ed,所以信号被捕获并且控制权在块之后下降.我们测试 die 是否确实是由于我们的警报引起的,如果不是,我们重新加注.

If your code completes in less than 5 seconds we get to alarm 0; which cancels the previous alarm and the program continues. Otherwise the SIGALRM is emitted, but is handled and made into a die which is eval-ed, and so altogether the signal is caught and the control drops to right after the block. We test whether the die was indeed due to our alarm and if not we re-raise it.

另请参阅这篇文章以获取更多评论,请搜索更多.

Also see this post for more comments, and please search for more.

IO::Socket 模块中存在的 Timeout 功能用于连接而不是用于 DNS 查找,这是罪魁祸首在这里.感谢 Steffen Ullrich 的评论.

  The Timeout functionality that exists in the module IO::Socket is for connect and not for the DNS lookup, which is the culprit here. Thanks to Steffen Ullrich for a comment.

这篇关于Perl 主机到 IP 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆