如何使用getaddrinfo()?

时间:2013-03-28 23:29:27

标签: winsock winsock2 getaddrinfo

我试图创建一个简单的程序,它接受像www.google.com这样的字符串并返回ip地址......

到目前为止:

char* hostname = new char[www.size()+1];
std::copy(www.begin(), www.end(), hostname);
hostname[www.size()] = '\0';

struct addrinfo new_addr, *res;

getaddrinfo(www.c_str(), SERVICE.c_str(), &new_addr, &res);



cout << new_addr.ai_addr;

第四个参数的第3个应该是什么? getaddrinfo函数是否修改new_addr结构或什么?我真的不明白msdn文档。主机名解析后,我想连接一个套接字。

2 个答案:

答案 0 :(得分:2)

如果我让第三个参数无效怎么办?

这是我迄今为止开发的代码。

    char* hostname = new char[www.size()+1];
copy(www.begin(), www.end(), hostname);
hostname[www.size()] = '\0';

struct addrinfo *res;
struct in_addr addr;

getaddrinfo(hostname, NULL, 0, &res);

addr.S_un = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.S_un;

server.sin_addr.s_addr = inet_addr(inet_ntoa(addr));
server.sin_port = htons(portno);

freeaddrinfo(res);
delete []hostname;

server.sin在其他地方声明,我用来填充套接字类的另一个方法中的套接字。

答案 1 :(得分:1)

MSDN文档非常详细,并准确说明了各种参数的用途。第三个参数允许您指定将与查找结果一起使用的套接字类型。这可以根据需要对结果进行优化。第四个参数返回实际结果。该文档还包含如何使用该功能的完整示例。那么什么样的例子不清楚文档说的是什么?

试试这个:

struct addrinfo hints = {0};
hints.ai_flags = 0;
hints.ai_family = AF_UNSPEC; // IPv4 and IPv6 allowed
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

struct addrinfo *res = NULL;

if (getaddrinfo(www.c_str(), SERVICE.c_str(), &hints, &res) == 0)
{
    TCHAR szIPAddr[64];
    DWORD szIPAddrLen;
    SOCKET skt;

    struct addrinfo *addr = res;
    do
    {
        skt = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
        if (skt == INVALID_SOCKET)
            cout << "Unable to create socket, error " << WSAGetLastError() << endl;
        else
        {
            szIPAddrLen = 64;
            WSAAddressToString(addr->ai_addr, addr->ai_addrlen, NULL, szIPAddr, &szIPAddrLen);

            cout << "Connecting to " << szIPAddr << " ..." << endl;

            if (connect(skt, addr->ai_addr, addr->ai_addrlen) == 0)
            {
                cout << "Connected!" << endl;
                break;
            }

            cout << "Unable to connect, error " << WSAGetLastError() << endl;
            closesocket(skt);
            skt = INVALID_SOCKET;
        }

        addr = addr->ai_next;
    }
    while (addr);

    freeaddrinfo(res);

    if (skt != INVALID_SOCKET)
    {
        // use skt as needed...
        closesocket(skt);
    }
}