在使用 `Socket` 编程时,虽然 `Socket` 本身只能处理 IP 地址,但可以通过 域名解析 将域名转换为对应的 IP 地址。以下是常见的域名解析方法和流程:
1、域名解析的基本流程
客户端发送请求:客户端向 DNS(Domain Name System)服务器发送域名解析请求。
DNS 服务器响应:DNS 服务器查找域名对应的 IP 地址,并将结果返回给客户端。
建立 Socket 连接:客户端使用获取到的 IP 地址与目标服务器建立 `Socket` 连接。
示例(C/C++ 中使用 `gethostbyname()`):
c
include <stdio.h
include <stdlib.h
include <string.h
include <sys/socket.h
include <netinet/in.h
include <arpa/inet.h
include <netdb.h
int main() {
struct hostent *he;
struct in_addr addr_list;
int i;
// 域名解析
he = gethostbyname(www.example.com);
if (!he) {
herror(gethostbyname);
exit(1);
}
// 获取 IP 地址列表
addr_list = (struct in_addr )heh_addr_list;
for (i = 0; addr_list[i] != NULL; i++) {
printf(IP Address: %s\n, inet_ntoa(*addr_list[i]));
}