nmap.cpp 2.6 KB

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