c/c++ 网络编程 getaddrinfo 函数

网络编程 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 : %s\n", err, gai_strerror(err));
    return 1;
  }
  addr.s_addr = ((sockaddr_in*)(res->ai_addr))->sin_addr.s_addr;
  printf("ip addresss: %s\n", inet_ntoa(addr));//博客园的网址,返回实际IP地址
  
  freeaddrinfo(res);

  return 0;
}

github源代码

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

posted @ 2018-10-09 23:25  小石王  阅读(4511)  评论(0编辑  收藏  举报