|
| 1 | +# 2. Go练习-fscan |
| 2 | + |
| 3 | +## 2.1. 存活主机顺序输出 |
| 4 | + |
| 5 | +Plugins目录下的icmp.go文件中CheckLive函数对应着探测存活主机功能,堆栈: |
| 6 | + |
| 7 | +``` |
| 8 | +Plugins.CheckLive (c:\Users\18846\Desktop\fscan\Plugins\icmp.go:23) |
| 9 | +Plugins.Scan (c:\Users\18846\Desktop\fscan\Plugins\scanner.go:27) |
| 10 | +main.main (c:\Users\18846\Desktop\fscan\main.go:15) |
| 11 | +``` |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +整体逻辑:`checkLive`函数中创建`chanHosts`通道,用channel接收多线程探测存活主机的结果。 |
| 16 | + |
| 17 | +修改:多线程里`chanHosts`中的IP不再实时输出,原本的打印逻辑注释掉,只保留扫描结果`AliveHosts` |
| 18 | + |
| 19 | +```go |
| 20 | +chanHosts := make(chan string, len(hostslist)) |
| 21 | + go func() { |
| 22 | + for ip := range chanHosts { |
| 23 | + if _, ok := ExistHosts[ip]; !ok && IsContain(hostslist, ip) { |
| 24 | + ExistHosts[ip] = struct{}{} |
| 25 | + // if common.Silent == false { |
| 26 | + // if Ping == false { |
| 27 | + // fmt.Printf("(icmp) Target %-15s is alive\n", ip) |
| 28 | + // } else { |
| 29 | + // fmt.Printf("(ping) Target %-15s is alive\n", ip) |
| 30 | + // } |
| 31 | + // } |
| 32 | + AliveHosts = append(AliveHosts, ip) |
| 33 | + } |
| 34 | + livewg.Done() |
| 35 | + } |
| 36 | + }() |
| 37 | +``` |
| 38 | + |
| 39 | +在`AliveHosts`返回之前对其进行排序并输出 |
| 40 | + |
| 41 | +```go |
| 42 | + // Sort the AliveHosts slice |
| 43 | + sort.Strings(AliveHosts) |
| 44 | + // Print sorted AliveHosts |
| 45 | + if Ping == false { |
| 46 | + for _, ip := range AliveHosts { |
| 47 | + fmt.Printf("(icmp) Target %-15s is alive\n", ip) |
| 48 | + } |
| 49 | + } else { |
| 50 | + for _, ip := range AliveHosts { |
| 51 | + fmt.Printf("(ping) Target %-15s is alive\n", ip) |
| 52 | + } |
| 53 | + } |
| 54 | + return AliveHosts |
| 55 | +``` |
| 56 | + |
| 57 | +缺点:要等到全部存活探测结束才有输出 |
| 58 | + |
| 59 | +优点:有排序,不会太乱 |
| 60 | + |
| 61 | +但是,结果跑出来发现排序不对 |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +修改一下排序的逻辑,不直接用`sort.Strings`了,使用`net`包中的`ParseIP`函数,解析一下IP再排序 |
| 66 | + |
| 67 | +```go |
| 68 | + // sort.Strings(AliveHosts) |
| 69 | + sort.Slice(AliveHosts, func(i, j int) bool { |
| 70 | + return bytes.Compare(net.ParseIP(AliveHosts[i]).To4(), net.ParseIP(AliveHosts[j]).To4()) < 0 |
| 71 | + }) |
| 72 | +``` |
| 73 | + |
| 74 | +这回应该没啥问题了,就是不知道效率被影响的程度,毕竟多解析了一遍IP,等用的时候再说吧 |
| 75 | + |
0 commit comments