查找用户所在的网络范围?

查找用户所在的网络范围?

我正在制作一个可以在任何网络上工作的网络扫描仪。这是我目前的代码

fd=$(date +%m%d%y%H%M%S)
echo -e "IP$fd\nReport of IP addresses on this intranet, test started at \n$(date)\n\nThe following IP addresses were found:" > IP$fd.txt
echo -e " Okay. Mind you, this could take a couple of minutes.\nI'll be scanning all 254 possibilities between 192.168.1.1 and 192.168.1.254\nI will ring the system bell when I am done.\nHere we go..."
for i in 192.168.0.{1..254}
do
echo "scanning $i"
if [ "$(ping -q -c1 $i)" ]
then
echo -e "AHA! Got one! ---- $i is up!"
fi
echo "END SCAN"
done
echo -e "That's all I got.\Test completed at\n$(date)\n" >> IP$fd.txt
echo -e \\a
echo -e "Your report is IP$fd.txt, and this is what it says:\n"
exit

但问题是,只有当您的 IP 范围是 192.168.0.1-255 时,此方法才有效。如果 IP 是 10.10.10.1,则不会返回任何内容。

有什么方法可以获取用户网络范围并将其应用到我的脚本中?

编辑:我以 root 身份运行

答案1

没有可移植的方式。

在 Linux 上,您可以使用以下命令列出主机所属的所有 IPv4 子网:

ip -4 route show scope link | awk '{print $1}'

(请注意,可能超过一个

答案2

您可以从输出中提取当前网络详细信息ifconfig -a

从此,您应该能够为 for 循环设置变量。使用整数地址可能比使用点分四组地址更容易。

将会有多个地址范围,其中一些是 IPV4,一些是 IPV6。

要检测当前机器未直接连接的附近网络需要做更多的工作。

相关内容