现在的位置: 首页 > 综合 > 正文

getaddrinfo, gethostbyname 寻址的函数

2014年10月06日 ⁄ 综合 ⁄ 共 1388字 ⁄ 字号 评论关闭

#include
#include

const char* c_port = "80";
const u_short i_port = 80;

int main()
{
        WORD wVersion = MAKEWORD(2,2);
        WSADATA        wsadata;
        int iresult = WSAStartup(wVersion, &wsadata);
        if(iresult != 0)
        {
                return iresult;
                WSACleanup();
        }
        if (LOBYTE(wsadata.wVersion) !=2 || LOBYTE(wsadata.wVersion) !=2)
        {
                WSACleanup();
                return 1;
        }

        struct addrinfo *result = NULL;
        struct addrinfo *ptr = NULL;
        struct addrinfo hints;
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;

        char host[MAX_PATH] = "www.baidu.com";

        //struct hostent* hent = (HOSTENT*)malloc(sizeof(HOSTENT));
        //hent  = gethostbyname("www.baidu.com");

        ZeroMemory(&hints, sizeof(addrinfo));
        int ret = getaddrinfo(host, c_port, &hints, &result);
        if (ret)
        {
                return WSAGetLastError();
        }
        ptr = result;
        struct sockaddr* addr = result->ai_addr;
        char sa[20] = {''};
        memcpy(sa, addr->sa_data, 14);
        int addr_len = result->ai_addrlen;

        SOCKET m_consock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

        iresult = connect(m_consock, ptr->ai_addr, (int)ptr->ai_addrlen);
        if(iresult == SOCKET_ERROR)
        {
                freeaddrinfo(ptr);
                return WSAGetLastError();
        }
        freeaddrinfo(ptr);

        return 0;
}

抱歉!评论已关闭.