套接字通讯实例(TCP)

来源:互联网 发布:windows7查看443端口 编辑:程序博客网 时间:2024/03/29 14:05
  1. #include "apue.h"
  2. #include <netdb.h>
  3. 转载请尊重原创、保留相关链接本文来自多宝平台http://www.mbodb.com
  4. /******************************客户端进程(Client.c)**********************************************/
  5. #include <sys/socket.h>

  6. #define BUFLEN 128
  7. #define QLEN 10

  8. int
  9. main(void)
  10. {
  11.   struct sockaddr_in ServerAdd;
  12.   int sockfd,err,clfd,n; 
  13.   char buf[256];
  14.   in_addr_t *hostip;
  15.   hostip=malloc(256);
  16.   /**************初始化服务端地址*****************/
  17.   ServerAdd.sin_family=AF_INET;
  18.   ServerAdd.sin_port=htons(6666);
  19.   memset(ServerAdd.sin_zero,0,8);
  20.   if((err=inet_pton(AF_INET,"127.0.0.1",(void*)hostip))!=1)
  21.     printf("inet_pton error\n");
  22.   ServerAdd.sin_addr.s_addr=*hostip;
  23.   /***********************************************/
  24.   if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)//创建套接字描述符
  25.     printf("sock error\n");
  26.   if(connect(sockfd,(struct sockaddr*)&ServerAdd,sizeof(struct sockaddr))<0)//与服务器建立连接
  27.     printf("connect error\n");
  28.   while((n=recv(sockfd,buf,256,0))>0)//等待接收服务器数据
  29.     write(STDOUT_FILENO,buf,n);
  30.   exit(0);
  31. }


点击(此处)折叠或打开

  1. /****************************服务器端进程(Server.c)***************************************/
  2. #include "apue.h"
  3. #include <netdb.h>
  4. #include <sys/socket.h>
  5. #include <errno.h>

  6. #define BUFLEN 128
  7. #define QLEN 10

  8. int
  9. main(void)
  10. {
  11.   struct sockaddr_in ServerAdd;
  12.   int sockfd,err,clfd;
  13.   char buf[]="hello client\n";
  14.   in_addr_t *hostip;
  15.   hostip=malloc(256);
  16.   /*********************初始化服务器端地址*****************************/
  17.   ServerAdd.sin_family=AF_INET;
  18.   ServerAdd.sin_port=htons(6666);
  19.   memset(ServerAdd.sin_zero,0,8);
  20.   if((err=inet_pton(AF_INET,"127.0.0.1",(void*)hostip))!=1)
  21.     printf("inet_pton error\n");
  22.   ServerAdd.sin_addr.s_addr=*hostip;
  23.    /**************************************************/
  24.   if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)//创建套接字描述符
  25.     printf("sock error\n");
  26.   if(bind(sockfd,(struct sockaddr*)&ServerAdd,sizeof(struct sockaddr))<0)//地址与描述符绑定
  27.     printf("bind error\n");
  28.   if(listen(sockfd,10)<0)//开始监听
  29.     printf("listen error\n");
  30.   if((clfd=accept(sockfd,NULL,NULL))<0)//阻塞,等待连接
  31.     printf("accept error:%s\n",strerror(errno));
  32.   send(clfd,buf,strlen(buf),0);//多宝有链接到达后发送数据
  33.   close(clfd);
  34. }

0 0
原创粉丝点击