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