在perl中查找子网中的所有IP [英] Find all IPs from subnet in perl

查看:144
本文介绍了在perl中查找子网中的所有IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带子网掩码的IP,并且想要创建一个表,其中每一行都是一个IP.

I have an IP with subnetmask and want to create a table in which every row is an IP.

这类的:

IP          | MAC  | Alive 
192.168.1.1 | ...  | yes
192.168.1.2 | ...  | no
192.168.1.3 | ...  | yes
...

对于子网/24的范围,这很容易,因为我可以生成一个从0到254的for循环,但是在生成带有/21子网的表时遇到了麻烦.是否可以在perl中找到最小主机,最大主机以及介于两者之间的所有内容?

For a range with subnet /24, this is easy because I can generate a for loop from 0 to 254 but I'm having trouble with generating the table with a /21 subnet. Is there a way to find in perl what the minimum host, the maximum host and everything in between is?

我已经检查了Net::IPNetAddr::IP模块,但是似乎无法解决我的问题.但是,我是perl新手,因此可能是我忽略了它.

I have checked the Net::IP and the NetAddr::IP module but don't seem a solution for my problem. However, I'm a perl newbie so it could be that I overlooked it.

找到了如何查找第一个和最后一个地址:

edit: found how to find first and last address:

my $range = "IP/subnet" ;
my $ip = new Net::IP ($range) || die;
print $ip->ip (), "\n";
print $ip->last_ip (), "\n";

现在我需要找到两者之间的IP地址

Now I need to find the IPs in between

推荐答案

Net::IP的文档在演示:

use Net::IP;

my $ip = new Net::IP("192.168.42.16/28");
do {
  print $ip->ip(), "\n";
} while (++$ip);

192.168.42.16
192.168.42.17
192.168.42.18
192.168.42.19
192.168.42.20
192.168.42.21
192.168.42.22
192.168.42.23
192.168.42.24
192.168.42.25
192.168.42.26
192.168.42.27
192.168.42.28
192.168.42.29
192.168.42.30
192.168.42.31

如果只有IP处于所需范围内,而没有前缀,则可以从地址和网络掩码中计算出前缀.尝试这样的事情(虽然可能有一种更聪明的方法可以通过Net::IP实现,但这使我难以理解):

If you only have an IP in the desired range, not the prefix, you can compute the prefix from the address and netmask. Try something like this (there probably is a more clever way of achieving this with Net::IP though, but that's eluding me):

use Net::IP;

my $addr = "192.168.42.23";
my $len  = 28;

my $mid = new Net::IP($addr, 4);
my $mask = Net::IP::ip_get_mask($len, 4);
my $first = $mid->binip() & $mask;
my $ip = new Net::IP(Net::IP::ip_bintoip($first, 4)."/$len", 4);
do {
  print $ip->ip(), "\n";
} while (++$ip);

这篇关于在perl中查找子网中的所有IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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