//./a.out ip port intmain(int argc,char *argv[]) { int sfd,cfd,ret; structsockaddr_insvr_addr,cli_addr; char buffer[1024] = {0}; ssize_t sbytes = 0,rbytes = 0; int length; int total_received; socklen_t len = sizeof(struct sockaddr_in); if (argc != 3){ fprintf(stderr,"Usage : %s < ip > < port >.\n",argv[0]) ; exit(EXIT_FAILURE); }
//1.创建套接字 sfd = socket(AF_INET,SOCK_STREAM,0); if (sfd == -1){ perror("[ERROR] Failed to socket."); exit(EXIT_FAILURE); }
bzero(&svr_addr,sizeof(struct sockaddr_in)); svr_addr.sin_family = AF_INET; svr_addr.sin_port = htons(atoi(argv[2])); svr_addr.sin_addr.s_addr = inet_addr(argv[1]); //2.绑定ip地址与端口号 ret = bind(sfd,(conststruct sockaddr *)&svr_addr,sizeof(struct sockaddr)); if (ret == -1){ perror("[ERROR] Failed to bind."); exit(EXIT_FAILURE); } //3.设置监听套接字为监听状态,建立监听队列 ret = listen(sfd,BACKLOG); if (ret == -1){ perror("[ERROR] Failed to listen."); exit(EXIT_FAILURE); }
//4.与客户端进行三次握手,并建立连接,默认是阻塞 cfd = accept(sfd,(struct sockaddr *)&cli_addr,&len); if (ret == -1){ perror("[ERROR] Failed to accpet."); exit(EXIT_FAILURE); }
printf("ip : %s port :%d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port)); for(;;){ length = 0; total_received = 0; //接收数据的长度 rbytes = recv(cfd,&length,4,0); if (rbytes == -1){ perror("[ERROR] Failed to recv."); exit(EXIT_FAILURE); } for(;;){
rbytes = recv(cfd,buffer + total_received,length - total_received,0); if (rbytes == -1){ perror("[ERROR] Failed to recv."); exit(EXIT_FAILURE); }elseif (rbytes == 0){ printf("The client has been shutdown.\n"); }elseif (rbytes > 0){ total_received += rbytes; if (total_received == length) break; } } printf("buffer : %s\n",buffer); sleep(1); }