3

i am using visual c++,

I want to get a domain ip address from domain name.. how do i get it.. i already tried gethostbyname function... here my code...

    HOSTENT* remoteHost;        
    IN_ADDR addr;       
    hostName = "domainname.com"; 
    printf("Calling gethostbyname with %s\n", hostName);
remoteHost =gethostbyname(hostName);
memcpy(&addr.S_un.S_addr, remoteHost->h_addr, remoteHost->h_length);
printf("The IP address is: %s\n", inet_ntoa(addr));

But i get a wrong ip address.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Arjun babu
  • 607
  • 2
  • 13
  • 42
  • What's a "domain IP address"? Hosts have both host names (which are a special case of domain names) and host IP addresses, but most entities with a domain name don't have an IP address. E.g. what's the IP address of `.com` ? – MSalters Jul 31 '12 at 14:32

1 Answers1

2

Here's complete source code to a little utility I find handy at times (I've named it "resolve"). All it does is resolve a domain name to a numeric IP (v4) address, and print it out. As-is, it's for Windows -- for Linux (or similar) you'd just need to get rid of the use_WSA class (and object thereof).

#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <iterator>
#include <exception>
#include <algorithm>
#include <iomanip>
#include "infix_iterator.h"

class use_WSA { 
    WSADATA d; 
    WORD ver;
public:
    use_WSA() : ver(MAKEWORD(1,1)) { 
        if ((WSAStartup(ver, &d)!=0) || (ver != d.wVersion))
            throw(std::runtime_error("Error starting Winsock"));
    }
    ~use_WSA() { WSACleanup(); }    
};

int main(int argc, char **argv) {
    if ( argc < 2 ) {
        std::cerr << "Usage: resolve <host-name>";
        return EXIT_FAILURE;
    }

    try { 
        use_WSA x;

        hostent *h = gethostbyname(argv[1]);
        unsigned char *addr = reinterpret_cast<unsigned char *>(h->h_addr_list[0]);
        std::copy(addr, addr+4, infix_ostream_iterator<unsigned int>(std::cout, "."));
    }
    catch (std::exception const &exc) {
        std::cerr << exc.what() << "\n";
        return EXIT_FAILURE;
    }

    return 0;
}

This also uses the infix_ostream_iterator I've posted previously.

Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111