【问题标题】:How to find Subnet of the given IP using perl cgi?如何使用 perl cgi 找到给定 IP 的子网?
【发布时间】:2013-05-23 05:15:00
【问题描述】:

我需要找到用户输入的任何 IP 的子网。我正在 perl 中执行“ypcat -k netmasks.byaddr”unix 命令来查找网络掩码。它在命令行执行中运行良好。但是在网络服务器中执行时它不起作用。

下面是代码。

use strict;
use CGI;
my $page=new CGI;

print $page->header;

my $ipaddress=$page->param("ip");
my @splitted=split(/\./,$ipaddress);

my $part1=$splitted[0].".".$splitted[1].".".$splitted[2];
my $part2=$splitted[3];

my $comma1="ypcat -k netmasks.byaddr|grep -w $part1|awk '{print \$1}'|awk -F. '{print \$4}'|sort -g";
my $comm2="ypcat -k netmasks.byaddr|grep -w $part1|sort";

my @out=`$comm1`;
my @out2=`$comm2`;

my $match;my $sub;my $found;
foreach my $i(@out){
        chomp($i);
        if($part2 > $i){
                $sub=$i;
                $found=$part1.".".$sub;
        }
}

my (@matched) = grep $_=~m/$found/, @out2;
chomp(@matched);
print "@matched\n";

以上是我用来查找给定 IP 的子网的代码。因为“$comm1”和“$comm2”的执行失败了。 是否有任何其他方法可以使用 Perl 脚本查找用户输入 IP 的子网?

谢谢, 马丹

【问题讨论】:

  • 什么“不工作”?如果您显示遇到问题的代码会有所帮助...
  • 嗨,pavel,我已经编辑了这个问题。
  • 您遇到什么错误? (检查您的网络服务器日志)。错误的一件事是您没有在输出之前打印任何 HTTP 标头...
  • 嗨 pavel....,服务器日志中没有错误。输出为空。但是,命令行执行正在完美返回。我忘记在此处提及 http 标头,但在我的代码中没有提及。
  • 您是否按照 pavel 的建议打印了页眉?

标签: perl unix cgi subnet


【解决方案1】:

您可以使用NetAddr::IP 模块来完成这项工作,如下所示:

#!/usr/local/bin/perl
use strict;
use warnings;
use CGI;
use NetAddr::IP;

my $page = new CGI;
print $page->header;
my $ipaddress = $page->param("ip");
my $ip = NetAddr::IP->new($ipaddress);
print "The address is ", $ip->addr, " with mask ", $ip->mask, "\n" ;

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2018-02-12
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多