我給出了application which uses Perl's gethostbyname
to check if a hostname exists in DNS。我不想修補不是由我寫的應用程序的源代碼。但我想在Perl編寫的配置文件之一中覆蓋gethostbyname
。是否可以在Perl中覆蓋或修改gethostbyname以支持IPv6?
所以我想知道是否有機會以某種方式猴子修補它。
的documentation of that application says that its hostname lookups work as follows:
$ perl -e 'print(gethostbyname("ipv6.google.com") ? "ok\n" : "not found\n");'
not found
到目前爲止,我嘗試:
$ perl -E 'use Socket qw(:DEFAULT getaddrinfo); sub gethostbyname { my ($err, @result) = getaddrinfo(@_); return @result; }; print(gethostbyname("ipv6.google.com") ? "ok\n" : "not found\n");'
not found
而且:
$ perl -E 'use Socket qw(:DEFAULT getaddrinfo); use Monkey::Patch::Action qw(patch_package); patch_package("*", "gethostbyname", "add", sub { my ($err, @result) = getaddrinfo(@_); return @result; }); print(gethostbyname("ipv6.google.com") ? "ok\n" : "not found\n");'
not found
(我也試過main
代替*
和replace
代替add
replace
跳傘如下:Replacing *::gethostbyname: must already exist at /usr/share/perl5/Monkey/Patch/Action.pm line 31.
)
在第二個片段中,你所需要的只是'use subs qw(gethostbyname);'。 – ikegami
在第三個片段中,我認爲用'BEGIN'包裝'patch_package'就可以了。 – ikegami
但是你可能想要從調用'gethostbyname'的模塊外面打補丁(或者你只需要調用正確的sub)。你可以通過命名你的覆蓋'CORE :: GLOBAL :: gethostbyname'(在使用'gethostbyname'的模塊被加載之前)來做到這一點。請參閱[覆蓋內置函數](https://perldoc.perl.org/perlsub.html#Overriding-Built-in-Functions)。您可以使用'caller'來僅提供覆蓋選擇模塊。 – ikegami