#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
// 定义一个简单的TCP客户端示例
int main() {
int sock;
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
int numbytes;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // 不指定IP版本,由系统自动选择
hints.ai_socktype = SOCK_STREAM; // 使用TCP协议
// 获取服务器的地址信息
if ((rv = getaddrinfo("example.com", "80", &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// 遍历所有返回的地址信息,尝试连接
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
close(sock);
perror("client: connect");
continue;
}
break; // 连接成功,退出循环
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
freeaddrinfo(servinfo); // 不再需要这个结构体
// 发送HTTP请求
const char *request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
if ((numbytes = send(sock, request, strlen(request), 0)) == -1) {
perror("send");
exit(1);
}
// 接收服务器响应
char buf[1024];
while ((numbytes = recv(sock, buf, sizeof buf - 1, 0)) > 0) {
buf[numbytes] = '\0';
printf("%s", buf);
}
if (numbytes == -1) {
perror("recv");
exit(1);
}
close(sock);
return 0;
}
<iostream>
, <cstring>
, <sys/types.h>
, <sys/socket.h>
, <netdb.h>
, <unistd.h>
是必要的系统头文件,用于处理网络通信和输入输出。socket()
函数创建一个套接字,该函数返回一个文件描述符(类似于文件句柄),用于后续的读写操作。getaddrinfo()
函数根据域名和端口号获取服务器的地址信息,并存储在 addrinfo
结构体中。connect()
函数用于建立与服务器的连接。如果连接失败,则继续尝试下一个地址。send()
函数向服务器发送HTTP GET请求。recv()
函数从服务器接收响应数据,并打印到标准输出。close()
函数关闭套接字。这段代码展示了如何用C++编写一个简单的TCP客户端,连接到一个HTTP服务器并获取网页内容。
上一篇:c++ gcd函数
下一篇:c++进制转换函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站