网络编程 getaddrinfo 函数
解析网址,返回ip地址。
例子:
#include <iostream> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h>//结构体addrinfo, in_addr #include <netinet/in.h> #include <arpa/inet.h> using namespace std; int main(){ char* hostname = "www.cnblogs.com";//博客园的网址,返回实际ip地址 addrinfo hints, *res; in_addr addr; int err; memset(&hints, 0, sizeof(addrinfo)); hints.ai_socktype = sock_stream; hints.ai_family = af_inet; if((err = getaddrinfo(hostname, null, &hints, &res)) != 0){ printf("error %d : %sn", err, gai_strerror(err)); return 1; } addr.s_addr = ((sockaddr_in*)(res->ai_addr))->sin_addr.s_addr; printf("ip addresss: %sn", inet_ntoa(addr));//博客园的网址,返回实际ip地址 freeaddrinfo(res); return 0; }
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607106.html