//getaddrinfo()函数原型 WINSOCK_API_LINKAGE INT WSAAPI getaddrinfo( _In_opt_ PCSTR pNodeName, //节点名可以是主机名,也可以是数字地址。(IPV4的10进点分,或是IPV6的16进制) _In_opt_ PCSTR pServiceName, //包含十进制数的端口号或服务名如(ftp,http) _In_opt_ const ADDRINFOA * pHints, //是一个空指针或指向addrinfo结构的指针,由调用者填写关于它所想返回的信息类型的线索 _Outptr_ PADDRINFOA * ppResult //存放返回addrinfo结构链表的指针 ); //调用该函数会获得一个addrinfo结构的列表,调用的返回值是addrinfo的结构(列表)指针。
//addrinfo结构原型typedef struct addrinfo { int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST int ai_family; // PF_xxx ,AF_INET,AF_INET6,AF_UNSPEC int ai_socktype; // SOCK_xxx ,SOCK_STREAM,SOCK_DGRAM int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6 ,IPPROTO_IP, IPPROTO_IPV4, IPPROTO_IPV6 etc. size_t ai_addrlen; // Length of ai_addr char * ai_canonname; // Canonical name for nodename _Field_size_bytes_(ai_addrlen) struct sockaddr * ai_addr; // Binary address struct addrinfo * ai_next; // Next structure in linked list } ADDRINFOA, *PADDRINFOA;
由getaddrinfo返回的所有存储空间都是动态获取的,这些存储空间必须通过调用freeaddrinfo返回给系统。
//freeaddrinfo()函数原型WINSOCK_API_LINKAGE VOID WSAAPI freeaddrinfo( _In_opt_ PADDRINFOA pAddrInfo );
//getaddrinfo()函数示例
char host_name[20] = "";
gethostname(host_name, 20);
ADDRINFOA hint, *pAddrinfo;
memset(&hint, 0, sizeof(ADDRINFOA));
hint.ai_family = AF_INET;
hint.ai_socktype = SOCK_STREAM;
hint.ai_protocol = IPPROTO_TCP;
hint.ai_flags = AI_PASSIVE;
int ret = getaddrinfo(host_name, "3050", &hint, &pAddrinfo);
if (ret!=0)
{
AfxMessageBox(_T("获得主机IP失败"));
return;
}
SOCKET socket_server = socket(pAddrinfo->ai_family, pAddrinfo->ai_socktype, pAddrinfo->ai_protocol);
bind(socket_server, pAddrinfo->ai_addr, pAddrinfo->ai_addrlen);
时间: 2024-11-03 05:30:04