• 文章
  • 獲取目標主機名的 IP 地址
釋出
2009 年 4 月 9 日(最後更新:2009 年 4 月 9 日)

獲取目標主機名的 IP 地址

評分:3.4/5(25 票)
*****
這是我在早期 C++ 經驗和學習過程中編寫的一些程式碼。已經進行了大約三週(我想)。這個小程式將獲取指定主機(在命令列中)的 IP 地址,並將時間戳、主機名和 IP 地址記錄到 ipaddr.log 檔案中。

未經廣泛測試;簡陋的程式碼。歡迎改進。

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