Skip to content

Instantly share code, notes, and snippets.

@lukas-h
Last active July 13, 2020 08:49
Show Gist options
  • Save lukas-h/78f4411437b09c20838e27e941c6e110 to your computer and use it in GitHub Desktop.
Save lukas-h/78f4411437b09c20838e27e941c6e110 to your computer and use it in GitHub Desktop.
Resolve IP as hostname (unix console tool)
/*
* `getip.c'
*
* Copyright (C) 2015, 2016 Lukas Himsel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Installation:
* Type `cc -O2 getip.c -o getip` into your console.
*
* Arguments & Usage:
* `getip <HOSTNAME>` for the standard output, with Hostname and IP, etc.
* `getip <HOSTNAME> --ip` prints only the IP address, nothing more.
*
*/
#include <stdio.h>
#include <arpa/inet.h>
#include <netdb.h>
int parse_args(int argc, char *argv[]);
int main(int argc, char *argv[]){
struct hostent *host;
struct in_addr *ip;
if(parse_args(argc, argv)){
puts("\033[1;34mgetip\033[0m <hostname> \033[32m[opts.]\033[0m\n options:\n \033[32m--ip\033[0m\tprint only IP addr.");
return 1;
}
host = gethostbyname(argv[1]);
if(host == NULL){
fprintf(stderr, "can not reach host: %s\n",argv[1]);
return 1;
}
ip = (struct in_addr *) host->h_addr;
if(argv[2]!=NULL){
if(strcmp(argv[2],"--ip")==0){
printf("%s\n", inet_ntoa(*ip));
}
} else{
printf("\033[1;34mHost:\033[0m %s\n\033[1;34mIP:\033[0m %s\n", host->h_name, inet_ntoa(*ip));
}
return 0;
}
int parse_args(int argc, char *argv[]){
if(argc < 2){
return 1;
}
if(strcmp(argv[1], "--help")==0 || strcmp(argv[1], "-h")==0){
return 1;
}
else{
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment