Selaa lähdekoodia

host: Use ArgsParser to parse arguments, and add man page (#1252)

Fixes #1246.
howar6hill 5 vuotta sitten
vanhempi
commit
83668299a6
2 muutettua tiedostoa jossa 36 lisäystä ja 10 poistoa
  1. 25 0
      Base/usr/share/man/man1/host.md
  2. 11 10
      Userland/host.cpp

+ 25 - 0
Base/usr/share/man/man1/host.md

@@ -0,0 +1,25 @@
+## Name
+
+host - DNS lookup utility
+
+## Synopsis
+
+```**sh
+$ host <name>
+```
+
+## 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
+```

+ 11 - 10
Userland/host.cpp

@@ -24,6 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include <LibCore/ArgsParser.h>
 #include <arpa/inet.h>
 #include <netdb.h>
 #include <netinet/in.h>
@@ -38,37 +39,37 @@ int main(int argc, char** argv)
         return 1;
     }
 
-    if (argc < 2) {
-        printf("usage: host <hostname>\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;
 }