Skip to content

Commit 7c995e8

Browse files
committed
Implement receiving commandline arguments; Improve goroutine.
1 parent 7853705 commit 7c995e8

1 file changed

Lines changed: 43 additions & 14 deletions

File tree

lmap.go

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package main
22

33
import (
4+
"os"
5+
"flag"
6+
"sort"
47
"bytes"
58
"encoding/binary"
69
"fmt"
@@ -23,37 +26,64 @@ type ICMP struct {
2326
}
2427

2528
func main() {
26-
wg.Add(1)
27-
go CheckIP()
28-
CheckIP()
29-
wg.Wait()
29+
isVerbose := false
30+
flag.BoolVar(&isVerbose, "v", false, "be verbose")
31+
flag.Parse()
32+
args := flag.Args()
33+
if len(args) < 1 {
34+
fmt.Printf("使用方法:%s [-v] <网络号>/<CIDR>\n", os.Args[0])
35+
os.Exit(-1)
36+
}
37+
CheckIP(os.Args[1], isVerbose)
3038
}
3139

32-
func CheckIP() {
33-
defer wg.Done()
40+
func CheckIP(subnet string, isVerbose bool) {
3441
var usedIP []string
3542
var unusedIP []string
3643
t := time.Now()
37-
hosts, _ := hosts("10.150.1.1/24")
44+
hosts, _ := getAllHostsFromCIDR(subnet)
3845
for _, ip := range hosts {
3946
tmp := ip
47+
time.Sleep(500)
48+
wg.Add(1)
4049
go func(data string) {
41-
bool := ping(data)
42-
if bool {
50+
defer wg.Done()
51+
isUsed := ping(data)
52+
if isUsed {
4353
usedIP = append(usedIP, data)
44-
fmt.Println("已使用IP:", usedIP)
54+
if isVerbose {
55+
fmt.Println("已使用IP:", usedIP)
56+
}
4557
} else {
4658
unusedIP = append(unusedIP, data)
47-
fmt.Println("未使用IP:", unusedIP)
59+
if isVerbose {
60+
fmt.Println("未使用IP:", unusedIP)
61+
}
4862
}
4963
}(tmp)
5064
}
5165
wg.Wait()
5266
elapsed := time.Since(t)
5367
fmt.Println("IP扫描完成,耗时", elapsed)
68+
fmt.Println("已使用IP:", sortIPList(usedIP))
69+
fmt.Println("未使用IP:", sortIPList(unusedIP))
70+
}
71+
72+
func sortIPList(ipStrings []string) (result []string) {
73+
var ips []net.IP
74+
for _, ipString := range ipStrings {
75+
ips = append(ips, net.ParseIP(ipString))
76+
}
77+
sort.Slice(ips, func(i, j int) bool {
78+
return bytes.Compare(ips[i], ips[j]) < 0
79+
})
80+
for _, ip := range ips {
81+
result = append(result, ip.String())
82+
}
83+
return
5484
}
5585

56-
func hosts(cidr string) ([]string, error) {
86+
func getAllHostsFromCIDR(cidr string) ([]string, error) {
5787
ip, ipnet, err := net.ParseCIDR(cidr)
5888
if err != nil {
5989
return nil, err
@@ -93,8 +123,7 @@ func ping(ip string) bool {
93123
buffer.Reset()
94124
binary.Write(&buffer, binary.BigEndian, icmp)
95125

96-
Time, _ := time.ParseDuration("1s")
97-
conn, err := net.DialTimeout("ip4:icmp", ip, Time)
126+
conn, err := net.DialTimeout("ip4:icmp", ip, 1 * time.Second)
98127
if err != nil {
99128
return false
100129
}

0 commit comments

Comments
 (0)