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