0

How to get domain name from Given IP in MFC (VC++) ? The code i am using is as below:

#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

// link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")


int _tmain(int argc, char **argv)
{

    //-----------------------------------------
    // Declare and initialize variables
    WSADATA wsaData = {0};
    int iResult = 0;

    DWORD dwRetval;

    struct sockaddr_in saGNI;
    char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;


// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return 1;
}
//-----------------------------------------
// Set up sockaddr_in structure which is passed
// to the getnameinfo function
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = inet_addr(argv[1]);
saGNI.sin_port = htons(port);

//-----------------------------------------
// Call getnameinfo
dwRetval = getnameinfo((struct sockaddr *) &saGNI,
                       sizeof (struct sockaddr),
                       hostname,
                       NI_MAXHOST, servInfo, NI_MAXSERV, NI_NUMERICSERV);

if (dwRetval != 0) {
    printf("getnameinfo failed with error # %ld\n", WSAGetLastError());
    return 1;
} else {
    printf("getnameinfo returned hostname = %s\n", hostname);
    return 0;
}

} This code is returning me hostname as = 255.255.255.255 not the domain name .

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
Swapnil Gupta
  • 8,751
  • 15
  • 57
  • 75

1 Answers1

0
int WSAAPI getnameinfo(
  __in   const struct sockaddr FAR *sa,
  __in   socklen_t salen,
  __out  char FAR *host,
  __in   DWORD hostlen,
  __out  char FAR *serv,
  __in   DWORD servlen,
  __in   int flags
);

http://msdn.microsoft.com/en-us/library/ms738532(v=VS.85).aspx

This API call deprecates gethostbyaddr.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
  • @Moo-Juice : Dude , i want domain name from IP not hostname. – Swapnil Gupta Nov 17 '10 at 12:16
  • I highly suggest you actually read the link I sent you. `A pointer to an ANSI string used to hold the host name. On success, the host name is returned as a Fully Qualified Domain Name (FQDN) ` ... – Moo-Juice Nov 17 '10 at 12:19
  • @Moo-Juice : I am getting hostname as 255.255.255.255 :( – Swapnil Gupta Nov 17 '10 at 12:29
  • I tried with your code, and for IP `212.58.244.57` I got `bbc-vip102.telhc.bbc.co.uk` . – Moo-Juice Nov 17 '10 at 12:40
  • @Swapnil, and just to confirm, that is the same result I got back from using `nslookup 212.58.244.57` from the command line. – Moo-Juice Nov 17 '10 at 13:16
  • @Moo-juice : Where i do need to pass my IP in the above code ? – Swapnil Gupta Nov 18 '10 at 03:49
  • This might be why you're having trouble... change `saGNI.sin_addr.s_addr = inet_addr(argv[1]);` to `saGNI.sin_addr.s_addr = inet_addr("212.58.244.57");` or run the program with the IP as an argument – Moo-Juice Nov 18 '10 at 07:42