I am in a Sockets programming (or Network Programming) class.
I'm using C++ as my language of choice, but need to know how to best approach the following scenario:
I need to prompt the user to enter either a DNS hostname or an ip address.
Upon doing so, the program must run the gethostbyname or gethostbyaddr function to output the correct information. The sample code provided is successful in achieving the goal, but requires the user to enter the host name within the code. I know I'll need to cin and cout and create a if \ then statement, but I have no idea of the proper approach.
// C++ DNS Processing (C++ Windows Version)
#include <iostream>
using namespace std;
#include <winsock.h>
int main(int argc, char **argv)
{
char *exampleHostName;
// Add the WSAStartup code...
// Winsock 1.1
WORD wVersionRequested = MAKEWORD(1,1);
WSADATA wsaData;
// Define the structure for the returned data
struct hostent *hostptr;
// Test case... change to other names or define in input variable
char *exampleHostName = "www.sunybroome.edu";
// Return code for the Winsock network startup
int nRet;
// Initialize the Winsock environment
nRet = WSAStartup(wVersionRequested, &wsaData);
// Check to make sure the environment initialized successfully
if(wsaData.wVersion != wVersionRequested)
{
cout << "Wrong version\n";
return 0;
}
if (hostptr = gethostbyname (exampleHostName) )
{
//
// The IP address is now in hostptr->h_addr
// Print out the contents of hostent structure
// in an easily readable form with labels. For
// example, the host name can be output using:
cout << "Host name: " << hostptr->h_name << endl;
}
else
{
//An error has occurred. Display an informative
//error message using the result of WSAGetLastError()
}
}
Thanks for the submission. The article helps.
However, my instructor actually wants us to add to the code so that the program prompts the user to add a domain (or an ip address). So the program would in effect be a two-way DNS name resolver - Input a domain name, output the resolved ip address, or vice-versa.