host.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/IPv4Address.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/System.h>
  9. #include <LibMain/Main.h>
  10. #include <arpa/inet.h>
  11. #include <netdb.h>
  12. #include <netinet/in.h>
  13. #include <string.h>
  14. ErrorOr<int> serenity_main(Main::Arguments args)
  15. {
  16. TRY(Core::System::pledge("stdio unix"));
  17. String name_or_ip {};
  18. Core::ArgsParser args_parser;
  19. args_parser.set_general_help("Convert between domain name and IPv4 address.");
  20. args_parser.add_positional_argument(name_or_ip, "Domain name or IPv4 address", "name");
  21. args_parser.parse(args);
  22. // If input looks like an IPv4 address, we should do a reverse lookup.
  23. auto ip_address = IPv4Address::from_string(name_or_ip);
  24. if (ip_address.has_value()) {
  25. // Okay, let's do a reverse lookup.
  26. auto addr = ip_address.value().to_in_addr_t();
  27. auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
  28. if (!hostent) {
  29. warnln("Reverse lookup failed for '{}'", name_or_ip);
  30. return 1;
  31. }
  32. outln("{} is {}", name_or_ip, hostent->h_name);
  33. return 0;
  34. }
  35. auto* hostent = gethostbyname(name_or_ip.characters());
  36. if (!hostent) {
  37. warnln("Lookup failed for '{}'", name_or_ip);
  38. return 1;
  39. }
  40. char buffer[INET_ADDRSTRLEN];
  41. char const* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer));
  42. outln("{} is {}", name_or_ip, ip_str);
  43. return 0;
  44. }