What Do You Think Of This Simple Nslookup? C++

What do you think of this code in terms of structure, and readability? Can you understand whats going on easily? Nothing fancy in here...

I tried to make the code talks about itself rather than writing unneeded
comments.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**program description:
 *
 * this is a simple nslook up program.
 * You simple enter the domain name
 * and the program gives you the ip
 * addresses associated with this
 * domain name, e.g. insert google.com,
 * you will get different set of IP
 * addresses that represents google.com
 * Works under Windows OS.
 *
 * Note: input is not validated, feel free
 * to customize the code
 *
 * Author: X-Shab
 *
 */

#include<iostream>
#include<string>
#include<sstream>
#include<Ws2tcpip.h>			   //used instead of "Winsock2.h"
using namespace std;

struct addrinfo hints;     
struct addrinfo *target;		   //holds full address information about the target domain

void initiateWinsockFacility()
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int error;

    wVersionRequested = MAKEWORD(2, 2);

    error = WSAStartup(wVersionRequested, &wsaData);

    if (error != 0) 
    {
        cout<<"WSAStartup failed with error: "<<error<<endl;
		system("pause");
        exit(-1);
    }
}

void getFullAddressInformation(const char *ipAddress)
{
	//output is sent to &target
	int status = getaddrinfo(ipAddress, NULL, &hints, &target);
	
	if(status != 0)
	{
		cout<<"getaddrinfo() error: "<< gai_strerror(status) <<endl;
		WSACleanup();
		system("pause");
		exit(-1);
	}
}

string nslookup(struct addrinfo *fetchIPsFromTarget)
{
	char printableIP[INET6_ADDRSTRLEN];

	struct sockaddr_in *ipv4 = (struct sockaddr_in *)fetchIPsFromTarget->ai_addr;
	void *ipAddress = &(ipv4->sin_addr);

	inet_ntop(ipv4->sin_family, ipAddress, printableIP, sizeof(printableIP));
	string ip(printableIP, strlen(printableIP));

	return ip;
}

int main()
{       
	initiateWinsockFacility();

	string targetDomain;
	cout<<"Please enter a domain name: ";
	cin>>targetDomain;

	memset(&hints, 0, sizeof(hints));

	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;

	getFullAddressInformation(targetDomain.c_str());

	//get all ip's associated with the target domain
	struct addrinfo *grabAllTargetIPs;
	for(grabAllTargetIPs = target; grabAllTargetIPs != NULL; grabAllTargetIPs = grabAllTargetIPs->ai_next)
	{
		string fetchedIP = nslookup(grabAllTargetIPs);
		cout<<fetchedIP<<endl;
	}

	freeaddrinfo(target);
	WSACleanup();

	cin.get();
	return 0;
}
Last edited on
system("pause") should be replaced with cin.get()
program is very easy to understand.. quite readable..
Good to know that. Thank you
Topic archived. No new replies allowed.