2020-01-18 08:38:21 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2022-04-16 20:46:28 +00:00
|
|
|
#include <AK/IPv4Address.h>
|
2020-02-20 14:12:55 +00:00
|
|
|
#include <LibCore/ArgsParser.h>
|
2022-01-13 20:39:44 +00:00
|
|
|
#include <LibCore/System.h>
|
|
|
|
#include <LibMain/Main.h>
|
2019-03-20 00:15:22 +00:00
|
|
|
#include <arpa/inet.h>
|
2019-06-07 09:49:31 +00:00
|
|
|
#include <netdb.h>
|
2019-03-20 00:15:22 +00:00
|
|
|
#include <netinet/in.h>
|
2019-06-07 09:49:31 +00:00
|
|
|
#include <string.h>
|
2019-03-20 00:15:22 +00:00
|
|
|
|
2022-01-13 20:39:44 +00:00
|
|
|
ErrorOr<int> serenity_main(Main::Arguments args)
|
2019-03-20 00:15:22 +00:00
|
|
|
{
|
2022-04-03 23:16:06 +00:00
|
|
|
TRY(Core::System::pledge("stdio unix"));
|
2020-01-11 19:49:31 +00:00
|
|
|
|
2023-12-16 14:19:34 +00:00
|
|
|
ByteString name_or_ip {};
|
2020-02-20 14:12:55 +00:00
|
|
|
Core::ArgsParser args_parser;
|
2020-12-05 15:22:58 +00:00
|
|
|
args_parser.set_general_help("Convert between domain name and IPv4 address.");
|
2020-02-20 14:12:55 +00:00
|
|
|
args_parser.add_positional_argument(name_or_ip, "Domain name or IPv4 address", "name");
|
2022-01-13 20:39:44 +00:00
|
|
|
args_parser.parse(args);
|
2019-03-20 00:15:22 +00:00
|
|
|
|
2019-06-06 03:35:03 +00:00
|
|
|
// If input looks like an IPv4 address, we should do a reverse lookup.
|
2022-04-16 20:46:28 +00:00
|
|
|
auto ip_address = IPv4Address::from_string(name_or_ip);
|
|
|
|
if (ip_address.has_value()) {
|
2019-06-06 03:35:03 +00:00
|
|
|
// Okay, let's do a reverse lookup.
|
2022-04-16 20:46:28 +00:00
|
|
|
auto addr = ip_address.value().to_in_addr_t();
|
|
|
|
auto* hostent = gethostbyaddr(&addr, sizeof(in_addr), AF_INET);
|
2019-06-06 03:35:03 +00:00
|
|
|
if (!hostent) {
|
2021-05-31 14:43:25 +00:00
|
|
|
warnln("Reverse lookup failed for '{}'", name_or_ip);
|
2019-06-06 03:35:03 +00:00
|
|
|
return 1;
|
|
|
|
}
|
2021-05-31 14:43:25 +00:00
|
|
|
outln("{} is {}", name_or_ip, hostent->h_name);
|
2019-06-06 03:35:03 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-07-11 20:42:03 +00:00
|
|
|
auto* hostent = gethostbyname(name_or_ip.characters());
|
2019-03-20 00:15:22 +00:00
|
|
|
if (!hostent) {
|
2021-05-31 14:43:25 +00:00
|
|
|
warnln("Lookup failed for '{}'", name_or_ip);
|
2019-03-20 00:15:22 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2021-02-09 21:35:00 +00:00
|
|
|
char buffer[INET_ADDRSTRLEN];
|
2022-04-01 17:58:27 +00:00
|
|
|
char const* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer));
|
2019-03-20 00:15:22 +00:00
|
|
|
|
2021-05-31 14:43:25 +00:00
|
|
|
outln("{} is {}", name_or_ip, ip_str);
|
2019-03-20 00:15:22 +00:00
|
|
|
return 0;
|
|
|
|
}
|