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

Fixes #1246.
This commit is contained in:
howar6hill 2020-02-20 22:12:55 +08:00 committed by GitHub
parent 088d7be19c
commit 83668299a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
Notes: sideshowbarker 2024-07-19 17:39:47 +09:00
2 changed files with 36 additions and 10 deletions

View file

@ -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
```

View file

@ -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;
}