【问题标题】:IP address conditional statement in perlperl中的IP地址条件语句
【发布时间】:2014-01-15 04:56:29
【问题描述】:

我们的系统中有一个 perl 脚本,用于验证我们组的 IP 地址。这是由以前的开发人员开发的,我不熟悉 perl。我们有一组 IP,它们是硬编码的,并在执行操作之前进行检查。这里是代码 sn-p(example)

unless ($remoteip eq "some ip" || $remoteip eq "some IP" || $remoteip eq   "xx.xx.xx.xx" )

现在我想添加另外 50 个范围内的 IP 地址(xx.xx.xx.145 到 xx.xx.xx.204) 我不想在 Unless 语句中一一添加它们,因为这会很长并且不利于编程(我认为)。有什么方法可以为 IP 地址添加 Less then 或 gratethen 语句?类似于除非($remoteip = "xx.xx.xx.145")。

谢谢。

【问题讨论】:

  • 不要认为这是 相当 重复,但你见过这个 SO 问题吗? How can I generate a range of IP addresses in Perl?
  • 您的问题可以改写为“地址是一个有效的 IP 地址,并以这三个八位字节开头,最后一个八位字节大于或等于 x 且小于或等于 y”。正如他们所说,实现它是一个简单的编程问题。 (一旦你想要跨越 /24 边界,事情就会变得更有趣。)

标签: perl ip-address conditional-statements


【解决方案1】:

将四边形转换为整数即可。 CPAN 上有一些模块可以为您完成,但归结为这样的事情

sub ip2dec ($) {
    unpack N => pack CCCC => split /\./ => shift;
}

if (ip2dec($remoteip) <= ip2dec('xx.xx.xx.204') && ip2dec($remoteip) >= ip2dec('xx.xx.xx.145')) {
   # do something
}

【讨论】:

  • 感谢这工作!我必须根据我的代码进行一些调整,但最终得到了它。
【解决方案2】:

您可以将 Socket 模块与 inet_aton 方法一起使用,并将范围转换为数组并通过 grep 查找。

use v5.16;
use strict;
use warnings;
use Socket qw/inet_aton/;
#using 10.210.14 as the first three octects
#convert range into binary
my @addressrange = map {unpack('N',inet_aton("10.210.14.$_"))} (145..204);
#address to test
my $address = $ARGV[0];
#grep for this binary in the range
unless(grep {unpack('N',inet_aton($address)) eq $_} @addressrange) {
  say "Address not part of the range"
}
else {
  say "Address is part of the range"
}

然后运行

perl iphelp.pl 10.210.14.15
Address not part of the range

perl iphelp.pl 10.210.14.145
Address is part of the range

【讨论】:

    【解决方案3】:

    自己处理逻辑没什么大不了的,但正如已经指出的那样,还有 CPAN 模块可以为您执行此操作。在这种情况下,为了简洁起见,我缩短了范围的长度:

    use strict;
    use warnings;
    use feature qw( say );
    
    use Net::Works::Address;
    
    my $lower = Net::Works::Address->new_from_string( string => '10.0.0.145' );
    my $upper = Net::Works::Address->new_from_string( string => '10.0.0.150' );
    
    foreach my $i ( 0 .. 255 ) {
        my $ip   = '10.0.0.' . $i;
        my $auth = check_ip( $ip );
        say "$ip is OK" if $auth;
    }
    
    sub check_ip {
        my $ip = shift;
        my $address = Net::Works::Address->new_from_string( string => $ip );
        return ( $address <= $upper && $address >= $lower );
    }
    

    输出是:

    10.0.0.145 is ok
    10.0.0.146 is ok
    10.0.0.147 is ok
    10.0.0.148 is ok
    10.0.0.149 is ok
    10.0.0.150 is ok
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多