2022-10-19

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值