【问题标题】:How to get domain name from Given IP in MFC (VC++)?如何从 MFC (VC++) 中的给定 IP 获取域名?
【发布时间】:2010-11-17 12:08:32
【问题描述】:

如何在 MFC (VC++) 中从给定 IP 获取域名? 我使用的代码如下:

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

} 此代码返回我的主机名 = 255.255.255.255 而不是域名。

【问题讨论】:

    标签: visual-c++ winapi winsock2 winsockets


    【解决方案1】:
    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

    此 API 调用已弃用 gethostbyaddr

    【讨论】:

    • @Moo-Juice : 老兄,我想要 IP 的域名而不是主机名。
    • 我强烈建议您实际阅读我发送给您的链接。 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 :我将主机名设为 255.255.255.255 :(
    • 我用你的代码试过了,IP 212.58.244.57 我得到了bbc-vip102.telhc.bbc.co.uk
    • @Swapnil,只是为了确认一下,这与我从命令行使用 nslookup 212.58.244.57 得到的结果相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2011-04-04
    • 2011-01-28
    • 1970-01-01
    • 2012-03-25
    • 2012-09-04
    相关资源
    最近更新 更多