#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
int main(int argc, char const *argv[])
{
char buf[128] = {0}; // 接收数据的缓冲区
int ret;
// 创建套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("socket creation error");
return -1;
}
printf("Socket created with fd: %d\n", sockfd);
struct sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr)); // 清空结构体
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8800); // 设置端口号
saddr.sin_addr.s_addr = inet_addr("192.168.51.20"); // 设置IP地址
// 绑定地址和端口
if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
{
perror("bind error");
close(sockfd); // 关闭套接字
return -1;
}
printf("Bind successful\n");
// 监听连接请求
if (listen(sockfd, 6) < 0)
{
perror("listen error");
close(sockfd); // 关闭套接字
return -1;
}
printf("Listening for connections\n");
// 接受客户端连接
int acceptfd = accept(sockfd, NULL, NULL);
if (acceptfd < 0)
{
perror("accept error");
close(sockfd); // 关闭套接字
return -1;
}
printf("Accepted connection with fd: %d\n", acceptfd);
while (1)
{
// 接收数据
ret = recv(acceptfd, buf, sizeof(buf), 0);
if (ret < 0)
{
perror("recv error");
close(acceptfd); // 关闭客户端连接套接字
close(sockfd); // 关闭监听套接字
return -1;
}
else if (ret == 0)
{
printf("Client disconnected\n");
break; // 客户端断开连接,退出循环
}
else
{
printf("Received data: %s\n", buf);
memset(buf, 0, sizeof(buf)); // 清空缓冲区
}
}
close(acceptfd); // 关闭客户端连接套接字
close(sockfd); // 关闭监听套接字
return 0;
}
05-19
2290
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-01
1450
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)