Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15851
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 20
  • 用 户 组: 普通用户
  • 注册时间: 2018-06-08 09:08
文章分类
文章存档

2018年(4)

我的朋友

分类: C/C++

2018-06-15 18:30:12

 /*服务端程序*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include


int main(void)
{
  int sockfd,ret,newfd;
  int readlen;
  int theirlen;
  char recv[100]={0};
  struct sockaddr_in myaddr;
  struct sockaddr_in theiraddr;
  if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
  {
    printf("socket failed(%s)\n", strerror(errno));
    exit(0);
  }
  memset(&myaddr,0,sizeof(myaddr));
  myaddr.sin_family=AF_INET;
  myaddr.sin_port =htons(3490);
  myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
  if((ret=bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
  {
     printf("bind failed\n");
         exit(0);
  }
  if((ret=listen(sockfd,10))  < 0)
  {
    printf("listen failed\n");
    exit(0);
   }
  theirlen=sizeof(theiraddr);
  if((newfd=accept(sockfd,(struct sockaddr *)&theiraddr,&theirlen))  < 0)
  {
    printf("accept failed\n");
    exit(0);
  }
  while(1)
  {
    memset(recv,0,sizeof(recv));
    readlen=read(newfd,recv,sizeof(recv));
    fputs(recv,stdout);
    write(newfd,recv,readlen);
  }
  close(newfd);
  close(sockfd);

  return 0;

}

 

/*客户端程序*/
#include
#include
#include
#include
#include
#include
#include
#include
#include


int main(void)
{
  int sockfd,ret;
  int readlen;
  char send[100]={0};
  char recv[100]={0};
  struct sockaddr_in myaddr;
  if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
  {
    printf("socket failed\n");
    exit(1);
  }
  memset(&myaddr,0,sizeof(myaddr));
  myaddr.sin_family=AF_INET;
  myaddr.sin_port =htons(3490);
  myaddr.sin_addr.s_addr=inet_addr("192.168.1.110");


  if((ret=connect(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
  {
     printf("connect failed\n");
              exit(1);
       }
  while(1)
  {
    memset(recv,0,sizeof(recv));
    memset(send,0,sizeof(send));
    if(fgets(send,sizeof(send),stdin) !=NULL)
    {
      write(sockfd,send,sizeof(send));
      read(sockfd,recv,sizeof(recv));
      fputs(recv,stdout);
    }
  }
  close(sockfd);
  return 0;
}

代码完整,可直运行

阅读(1458) | 评论(0) | 转发(0) |
0

上一篇:计算机网络【三】:数据链路层

下一篇:没有了

给主人留下些什么吧!~~