通过域名进行socket

请问如何利用SOCKET解析域名?
 比如我的一台服务器是绑定了域名,那些客户端想和服务器进行通信,但只能通过域名来通信。
 那该如何利用SOCKET靠域名和服务器通信啊?

  1. #pragma comment(lib, "ws2_32")

  2. #include <winsock2.h>
  3. #include <stdio.h>
  4. #include <assert.h>

  5. int main()
  6. {
  7.     struct hostent *host;
  8.     WSADATA wsaData;
  9.     int ret;

  10.     ret = WSAStartup(0x0202, &wsaData);
  11.     if(ret)
  12.     {
  13.         printf("error in WSAStartup: %d ", WSAGetLastError());
  14.         return 0;
  15.     }

  16.     host = gethostbyname("www.baidu.com");
  17.     if(host == NULL)
  18.     {
  19.         printf("error in gethostbyname: %d ", WSAGetLastError());
  20.     }
  21.     else
  22.     {
  23.         printf("name: %s addrtype; %d addrlength: %d ",
  24.             host->h_name, host->h_addrtype, host->h_length);
  25.         printf("ip address: %s ",
  26.             inet_ntoa(*(struct in_addr*)host->h_addr_list[0]));
  27.     }

  28.     WSACleanup();
  29.     return 0;
  30. }

 输出:
 name: www.a.shifen.com
 addrtype; 2
 addrlength: 4
 ip address: 202.108.22.5

阅读(850) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/black/p/5171854.html