1
0

nmap.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "nmap.h"
  4. #include "hthreadpool.h"
  5. int host_discovery_task(std::string segment, void* nmap) {
  6. Nmap* hosts= (Nmap*)nmap;
  7. return host_discovery(segment.c_str(), hosts);
  8. }
  9. int main(int argc, char* argv[]) {
  10. if (argc < 2) {
  11. printf("Usage: cmd segment\n");
  12. printf("Examples: nmap 192.168.1.123\n");
  13. printf(" nmap 192.168.1.x/24\n");
  14. printf(" nmap 192.168.x.x/16\n");
  15. return -1;
  16. }
  17. char* segment = argv[1];
  18. char* split = strchr(segment, '/');
  19. int n = 24;
  20. if (split) {
  21. *split = '\0';
  22. n = atoi(split+1);
  23. if (n != 24 && n != 16) {
  24. return -2;
  25. }
  26. }
  27. if (n == 24) {
  28. Nmap nmap;
  29. int ups = host_discovery(segment, &nmap);
  30. return 0;
  31. }
  32. char ip[INET_ADDRSTRLEN];
  33. if (n == 16) {
  34. Nmap nmap;
  35. int up_nsegs = segment_discovery(segment, &nmap);
  36. if (up_nsegs == 0) return 0;
  37. if (up_nsegs == 1) {
  38. for (auto& pair : nmap) {
  39. if (pair.second == 1) {
  40. inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip));
  41. Nmap hosts;
  42. return host_discovery(ip, &hosts);
  43. }
  44. }
  45. }
  46. Nmap* hosts = new Nmap[up_nsegs];
  47. // use ThreadPool
  48. HThreadPool tp(4);
  49. tp.start();
  50. std::vector<std::future<int>> futures;
  51. int i = 0;
  52. for (auto& pair : nmap) {
  53. if (pair.second == 1) {
  54. inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip));
  55. auto future = tp.commit(host_discovery_task, std::string(ip), &hosts[i++]);
  56. futures.push_back(std::move(future));
  57. }
  58. }
  59. // wait all task done
  60. int nhosts = 0;
  61. for (auto& future : futures) {
  62. nhosts += future.get();
  63. }
  64. // filter up hosts
  65. std::vector<uint32_t> up_hosts;
  66. for (int i = 0; i < up_nsegs; ++i) {
  67. Nmap& nmap = hosts[i];
  68. for (auto& host : nmap) {
  69. if (host.second == 1) {
  70. up_hosts.push_back(host.first);
  71. }
  72. }
  73. }
  74. delete[] hosts;
  75. // print up hosts
  76. printf("Up hosts %d:\n", nhosts);
  77. for (auto& host : up_hosts) {
  78. inet_ntop(AF_INET, (void*)&host, ip, sizeof(ip));
  79. printf("%s\n", ip);
  80. }
  81. }
  82. return 0;
  83. }