这是一段极其简单的代码,调用 Windows Socket API(Winsock)发送了一段 HTTP 请求,并把相应的 HTTP 响应输出到了标准输出设备上。如果编译时定义了 _UNICODE 或 UNICODE 宏,GetAddrInfo 展开后会成为 GetAddrInfoW,而这是一个新函数,Windows Vista、Windows XP SP2 或 Windows Server 2003 以后的操作系统才支持。实际应用的时候,需要处理各种函数可能导致的错误。HTTP 请求报头也会随着需求改变而不同,这里是向 http://www.66rpg.com:80 发送请求,之后服务器端会发送回正文包含了 66rpg 主页 HTML 文档的 HTTP 响应。BUF_LEN 这个宏指定了每次接收数据用的缓冲区大小,这里使用了一个小数字,方便测试循环的正确性。
#include <stdio.h> #include <winsock2.h> #include <Ws2tcpip.h> #define BUF_LEN 16 void main() { WSADATA wsa_data; ADDRINFOT *addr_info; SOCKET sock; char *http_request; char buf[BUF_LEN]; int byte_count; WSAStartup(0x0202, &wsa_data); GetAddrInfo(TEXT("www.66rpg.com"), TEXT("http"), NULL, &addr_info); sock = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); connect(sock, addr_info->ai_addr, addr_info->ai_addrlen); http_request = "GET http://www.66rpg.com/ HTTP/1.1\n" "Host: www.66rpg.com\n" "Connection: close\n" "\n"; printf("%s\n", http_request); send(sock, http_request, strlen(http_request), 0); do { byte_count = recv(sock, buf, BUF_LEN, 0); fwrite(buf, 1, byte_count, stdout); } while (byte_count > 0); printf("\n"); freeaddrinfo(addr_info); closesocket(sock); WSACleanup(); }
输出:
GET http://www.66rpg.com/ HTTP/1.1 Host: www.66rpg.com Connection: close HTTP/1.1 200 OK Connection: close Date: Mon, 27 Dec 2010 20:52:33 GMT Content-Length: 1299 Content-Type: text/html Content-Location: http://www.66rpg.com/index.htm Last-Modified: Tue, 28 Sep 2010 22:28:28 GMT Accept-Ranges: bytes ETag: "16641a795c5fcb1:107f6" Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET <html> <title>66RPG</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <meta name="keywords" content="格斗纹章,柳柳,66RPG,战棋,新战棋,游戏,单机游戏,原 创游戏" /> <head> <style type="text/css"> <!-- a:link { text-decoration: none;color: blue} a:active{ text-decoration:blink} a:hover{ text-decoration:underline; color: red} a:visited{ text-decoration:none; color:green} --> </style> </head> <body bgcolor="#DDDDFF"> <p align=center>66RPG</p> <p align=center>这里只是一个链接汇总,想去哪里,请点击下面的传送门。</p> <p align=center><a href=http://bbs.66rpg.com/ target="_blank"><font color=red>★ 66RPG 论坛 ★</font></a><br><font color=gray>http://bbs.66rpg.com/</font></p> <p align=center><a href=http://bbs.66rpg.com/portal.php target="_blank"><font co lor=red>★ 66RPG 主站(建设中) ★</font></a><br><font color=gray>http://bbs.66r pg.com/portal.php</font></p> <p align=center><a href=http://bbs.66rpg.com/thread-153776-1-1.html target="_bla nk"><font color=red>★ 66RPG 资源帖 ★</font></a><br><font color=gray>http://bbs .66rpg.com/thread-153776-1-1.html</font></p> <p align=center><a href=http://www.66rpg.com/GD target="_blank"><font color=red> ★ 格斗纹章 传送门 ★</font></a><br><font color=gray>http://www.66rpg.com/GD</fo nt></p> </body> </html>