• Articles
  • Get IP address of target hostname
Published by
Apr 9, 2009 (last update: Apr 9, 2009)

Get IP address of target hostname

Score: 3.3/5 (24 votes)
*****
Some code I came up with during the conception of my early C++ experience and learning. Going on three weeks now (I think). This little program will grab the IP address of the specified host (on the command line), and log the timestamp, hostname and IP address to ipaddr.log.

Has not been extensively tested; barebones code. Improvements are welcomed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <netdb.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fstream>
#include <time.h>
using namespace std;

#define MST (-7)

int main(int argc, char *argv[])
{
	if(argc != 2)
	{
		printf("usage: %s <hostname>\n", argv[0], argv[1]);
		exit(1);
	}
		
	hostent * record = gethostbyname(argv[1]);
	if(record == NULL)
	{
		printf("%s is unavailable\n", argv[1]);
		exit(1);
	}
	in_addr * address = (in_addr * )record->h_addr;
	string ip_address = inet_ntoa(* address);

	// get the current time
	time_t rawtime;
	tm * ptm;
	time ( &rawtime );
	ptm = gmtime ( &rawtime );
	
	cout << argv[1] << " (" << ip_address << ")\n";
	
	// log this information to ipaddr.log
	ofstream ipaddr_log("ipaddr.log", ios::app);
	ipaddr_log << (ptm->tm_hour+MST%24) << ":" << (ptm->tm_min) << " " << argv[1] << " (" << ip_address << ")" << endl;
	ipaddr_log.close();
	return 0;
}