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
|
|
|
*/
|
|
|
|
|
2020-02-20 14:12:55 +00:00
|
|
|
#include <LibCore/ArgsParser.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>
|
|
|
|
#include <stdio.h>
|
2019-06-07 09:49:31 +00:00
|
|
|
#include <string.h>
|
2020-01-11 19:49:31 +00:00
|
|
|
#include <unistd.h>
|
2019-03-20 00:15:22 +00:00
|
|
|
|
|
|
|
int main(int argc, char** argv)
|
|
|
|
{
|
2021-01-22 17:42:57 +00:00
|
|
|
if (pledge("stdio unix", nullptr) < 0) {
|
2020-01-11 19:49:31 +00:00
|
|
|
perror("pledge");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2020-02-20 14:12:55 +00:00
|
|
|
const char* name_or_ip = nullptr;
|
|
|
|
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");
|
|
|
|
args_parser.parse(argc, argv);
|
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.
|
|
|
|
struct sockaddr_in addr;
|
|
|
|
memset(&addr, 0, sizeof(addr));
|
|
|
|
addr.sin_family = AF_INET;
|
|
|
|
addr.sin_port = htons(53);
|
2020-02-20 14:12:55 +00:00
|
|
|
int rc = inet_pton(AF_INET, name_or_ip, &addr.sin_addr);
|
2019-06-06 03:35:03 +00: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 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;
|
|
|
|
}
|
|
|
|
|
2020-02-20 14:12:55 +00:00
|
|
|
auto* hostent = gethostbyname(name_or_ip);
|
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];
|
2019-03-20 00:15:22 +00:00
|
|
|
const char* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer));
|
|
|
|
|
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;
|
|
|
|
}
|