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