Debian Codegraph @

third-party/libhv-v1.3.3/examples/nmap/main.cpp

raw
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include <string>
5
6 #include "nmap.h"
7 #include "hsocket.h"
8 #include "hthreadpool.h"
9
10 int host_discover_task(std::string segment, void* nmap) {
11 Nmap* hosts= (Nmap*)nmap;
12 return host_discover(segment.c_str(), hosts);
13 }
14
15 int main(int argc, char* argv[]) {
16 if (argc < 2) {
17 printf("Usage: nmap segment\n");
18 printf("Examples: nmap 192.168.1.123\n");
19 printf(" nmap 192.168.1.x/24\n");
20 printf(" nmap 192.168.x.x/16\n");
21 return -1;
22 }
23
24 char* segment = argv[1];
25 char* split = strchr(segment, '/');
26 int n = 24;
27 if (split) {
28 *split = '\0';
29 n = atoi(split+1);
30 if (n != 24 && n != 16) {
31 return -2;
32 }
33 }
34
35 Nmap hosts;
36 char ip[INET_ADDRSTRLEN];
37 if (n == 24) {
38 host_discover(segment, &hosts);
39 }
40 else if (n == 16) {
41 Nmap segs;
42 int up_nsegs = segment_discover(segment, &segs);
43 if (up_nsegs == 0) return 0;
44 #if 1
45 for (auto& pair : segs) {
46 if (pair.second == 1) {
47 uint32_t addr = pair.first;
48 uint8_t* p = (uint8_t*)&addr;
49 // 0,255 reserved
50 for (int i = 1; i < 255; ++i) {
51 p[3] = i;
52 hosts[addr] = 0;
53 }
54 }
55 }
56 nmap_discover(&hosts);
57 #else
58 if (up_nsegs == 1) {
59 for (auto& pair : segs) {
60 if (pair.second == 1) {
61 inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip));
62 host_discover(ip, &hosts);
63 }
64 }
65 }
66 else {
67 // ThreadPool + host_discover
68 Nmap* hosts = new Nmap[up_nsegs];
69 // use ThreadPool
70 HThreadPool tp(4);
71 tp.start();
72 std::vector<std::future<int>> futures;
73 int i = 0;
74 for (auto& pair : segs) {
75 if (pair.second == 1) {
76 inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip));
77 auto future = tp.commit(host_discover_task, std::string(ip), &hosts[i++]);
78 futures.push_back(std::move(future));
79 }
80 }
81 // wait all task done
82 int nhosts = 0;
83 for (auto& future : futures) {
84 nhosts += future.get();
85 }
86 // filter up hosts
87 std::vector<uint32_t> up_hosts;
88 for (int i = 0; i < up_nsegs; ++i) {
89 Nmap& nmap = hosts[i];
90 for (auto& host : nmap) {
91 if (host.second == 1) {
92 up_hosts.push_back(host.first);
93 }
94 }
95 }
96 delete[] hosts;
97 }
98 #endif
99 }
100
101 // filter up hosts
102 std::vector<uint32_t> up_hosts;
103 for (auto& pair : hosts) {
104 if (pair.second == 1) {
105 up_hosts.push_back(pair.first);
106 }
107 }
108 // print up hosts
109 printf("Up hosts %lu:\n", (unsigned long)up_hosts.size());
110 for (auto& host : up_hosts) {
111 inet_ntop(AF_INET, (void*)&host, ip, sizeof(ip));
112 printf("%s\n", ip);
113 }
114 return 0;
115 }