找出子网中最长连续可用IP

昨天的一道面试题,要求找出一个网段中最长的连续可用IP,需要考虑关机的但已经静态分配了IP的机器。

当时用ping找出了能ping通的IP,但是没有想到怎么找出最长的连续段,并且不模拟多线程会比较慢。现在先不考虑关机的情况,用nmap做一遍。代码如下:

#!/bin/bash

#-----------------------------------------------------------
# Usage: 找出子网中最长连续可用ip
# $Id: continuous-ip-baidu.sh  i@annhe.net  2015-08-04 12:06:11 $
#-----------------------------------------------------------

subnet="192.168.60.0/24"

used=(`nmap -sP -n $subnet |grep report |awk -F "." '{print $NF}'`)

echo "used: ${used[*]}"
num=${#used[*]}

let max=${used[1]}-${used[0]}
continuous="${used[0]} -> ${used[1]}"
for [1]i=0; i<num-1; i++; do
    let next=i+1
    let sum=${used[next]}-${used[i]}
    if [ $sum -gt $max ]; then
        max=$sum
        continuous="${used[$i]} -> ${used[$next]}"
    fi
done

echo -e "\n$continuous -- max:$max"

结果如下:

[root@HADOOP-215 interview]# ./continuous-ip-baidu.sh 
used: 1 2 129 254

2 -> 129 -- max:127

参考资料

参考资料
1 i=0; i<num-1; i++

4 thoughts on “找出子网中最长连续可用IP

    • 是这样查吗?[root@HADOOP-215 ~]# dig -x 216.58.221.142; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.3 <<>> -x 216.58.221.142;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27880;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 4, ADDITIONAL: 4;; QUESTION SECTION:;142.221.58.216.in-addr.arpa. IN PTR;; ANSWER SECTION:142.221.58.216.in-addr.arpa. 5 IN PTR hkg07s02-in-f14.1e100.net.142.221.58.216.in-addr.arpa. 5 IN PTR hkg07s02-in-f142.1e100.net.;; AUTHORITY SECTION:221.58.216.in-addr.arpa. 5 IN NS ns3.google.com.221.58.216.in-addr.arpa. 5 IN NS ns4.google.com.221.58.216.in-addr.arpa. 5 IN NS ns1.google.com.221.58.216.in-addr.arpa. 5 IN NS ns2.google.com.;; ADDITIONAL SECTION:ns1.google.com. 5 IN A 216.239.32.10ns2.google.com. 5 IN A 216.239.34.10ns3.google.com. 5 IN A 216.239.36.10ns4.google.com. 5 IN A 216.239.38.10;; Query time: 8 msec;; SERVER: 192.168.60.2#53(192.168.60.2);; WHEN: Fri Aug 7 18:41:07 2015;; MSG SIZE rcvd: 261

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注