From 83668299a61c39556976d731fcf7d04466157f2a Mon Sep 17 00:00:00 2001 From: howar6hill Date: Thu, 20 Feb 2020 22:12:55 +0800 Subject: [PATCH] host: Use ArgsParser to parse arguments, and add man page (#1252) Fixes #1246. --- Base/usr/share/man/man1/host.md | 25 +++++++++++++++++++++++++ Userland/host.cpp | 21 +++++++++++---------- 2 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 Base/usr/share/man/man1/host.md diff --git a/Base/usr/share/man/man1/host.md b/Base/usr/share/man/man1/host.md new file mode 100644 index 0000000000..c76d15192e --- /dev/null +++ b/Base/usr/share/man/man1/host.md @@ -0,0 +1,25 @@ +## Name + +host - DNS lookup utility + +## Synopsis + +```**sh +$ host +``` + +## Description + +`host` is a simple utility for performing DNS lookups. It is used to +convert names to IP addresses and vice versa. + +`name` is the domain name that is to be looked up. It can also be a +dotted-decimal IPv4 address, in which case `host` will perform a reverse +lookup for that address. + +## Examples + +```sh +$ host github.com +$ host 8.8.8.8 +``` diff --git a/Userland/host.cpp b/Userland/host.cpp index 39c605265e..6f3bed6fe0 100644 --- a/Userland/host.cpp +++ b/Userland/host.cpp @@ -24,6 +24,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include #include @@ -38,37 +39,37 @@ int main(int argc, char** argv) return 1; } - if (argc < 2) { - printf("usage: host \n"); - return 0; - } + const char* name_or_ip = nullptr; + Core::ArgsParser args_parser; + args_parser.add_positional_argument(name_or_ip, "Domain name or IPv4 address", "name"); + args_parser.parse(argc, argv); // 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); - int rc = inet_pton(AF_INET, argv[1], &addr.sin_addr); + int rc = inet_pton(AF_INET, name_or_ip, &addr.sin_addr); if (rc == 1) { // Okay, let's do a reverse lookup. auto* hostent = gethostbyaddr(&addr.sin_addr, sizeof(in_addr), AF_INET); if (!hostent) { - fprintf(stderr, "Reverse lookup failed for '%s'\n", argv[1]); + fprintf(stderr, "Reverse lookup failed for '%s'\n", name_or_ip); return 1; } - printf("%s is %s\n", argv[1], hostent->h_name); + printf("%s is %s\n", name_or_ip, hostent->h_name); return 0; } - auto* hostent = gethostbyname(argv[1]); + auto* hostent = gethostbyname(name_or_ip); if (!hostent) { - fprintf(stderr, "Lookup failed for '%s'\n", argv[1]); + fprintf(stderr, "Lookup failed for '%s'\n", name_or_ip); return 1; } char buffer[32]; const char* ip_str = inet_ntop(AF_INET, hostent->h_addr_list[0], buffer, sizeof(buffer)); - printf("%s is %s\n", argv[1], ip_str); + printf("%s is %s\n", name_or_ip, ip_str); return 0; }