#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#define PORT 8000
#define IP "192.168.126.140"
#define PRINT_ERR(msg) \
do \
{ \
perror("msg"); \
return -1; \
} while (0)
int main(int argc, const char *argv[])
{
int sfd = socket(AF_INET, SOCK_STREAM, 0); // 创建 socket 套接字;
if (sfd == -1)
PRINT_ERR("socket");
struct sockaddr_in sin; // 地址结构体
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
if (0 > bind(sfd, (struct sockaddr *)&sin, sizeof(sin))) // 绑定自己 IP 和 端口
PRINT_ERR("bind");
if (listen(sfd, 100)) // 单次最多发送 100 个长度
PRINT_ERR("listen");
int newfd1 = accept(sfd, NULL, NULL); // 开启一块新的空间和其描述符
if (-1 == newfd1)
PRINT_ERR("accept");
else
printf("链接已建立\n");
char buff[100] = {0}; // 接受和打印消息的变量
int res;
while (res = recv(newfd1, &buff, sizeof(buff), 0))
{
if(-1 == res)
PRINT_ERR("recv");
// printf("res = %d\n",res);
buff[res] = '\0';
printf("%s\n",buff);
send(newfd1,buff,sizeof(buff),0);
}
printf("对方已退出\n");
close(sfd);
close(newfd1);
return 0;
}
2022-10-19
最新推荐文章于 2024-08-02 17:56:54 发布