TCP编程实现LINUX平台文件传输工程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP编程实现LINUX平台文件传输工程相关的知识,希望对你有一定的参考价值。
server端代码
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <unistd.h> 6 #include <sys/types.h> 7 #include <sys/socket.h> 8 #include <netinet/in.h> 9 #include <arpa/inet.h> 10 11 #define MAXLINE 1024 12 13 void usage(char *command) 14 { 15 printf("usage :%s portnum filename\n", command); 16 exit(0); 17 } 18 int main(int argc,char **argv) 19 { 20 struct sockaddr_in serv_addr; 21 struct sockaddr_in clie_addr; 22 char buf[MAXLINE]; 23 int sock_id; 24 int link_id; 25 int recv_len; 26 int write_leng; 27 int clie_addr_len; 28 FILE *fp; 29 30 if (argc != 3) { 31 usage(argv[0]); 32 } 33 /*<-----------------------------------------socket---------------------------------------------->*/ 34 if ((sock_id = socket(AF_INET, SOCK_STREAM, 0)) < 0) 35 { 36 perror("Create socket failed\n"); 37 exit(0); 38 } 39 /*<-----------------------------------------bind------------------------------------------------->*/ 40 memset(&serv_addr, 0, sizeof(serv_addr)); 41 serv_addr.sin_family = AF_INET; 42 serv_addr.sin_port = htons(atoi(argv[1])); 43 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 44 45 if (bind(sock_id, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 ) 46 { 47 perror("Bind socket failed\n"); 48 exit(0); 49 } 50 /*<-----------------------------------------listen----------------------------------------------->*/ 51 if (-1 == listen(sock_id, 10)) 52 { 53 perror("Listen socket failed\n"); 54 exit(0); 55 } 56 /*<-------------------------------------server receive part---------------------------------->*/ 57 while (1) { 58 if ((fp = fopen(argv[2], "w")) == NULL) 59 { 60 perror("Open file failed\n"); 61 exit(0); 62 } 63 lseek(fp, 0, SEEK_END); 64 clie_addr_len = sizeof(clie_addr); 65 /*<-----------------------------------------accept----------------------------------------------->*/ 66 link_id = accept(sock_id, (struct sockaddr *)&clie_addr, &clie_addr_len); 67 if (-1 == link_id) { 68 perror("Accept socket failed\n"); 69 exit(0); 70 } 71 bzero(buf, MAXLINE); 72 while (recv_len = recv(link_id, buf, MAXLINE, 0)) 73 { 74 if(recv_len < 0) 75 { 76 printf("Recieve Data From Server Failed!\n"); 77 break; 78 } 79 printf("#"); 80 write_leng = fwrite(buf, sizeof(char), recv_len, fp); 81 if (write_leng < recv_len) 82 { 83 printf("Write file failed\n"); 84 break; 85 } 86 bzero(buf,MAXLINE); 87 } 88 printf("\nFinish Recieve\n"); 89 fclose(fp); 90 close(link_id); 91 } 92 close(sock_id); 93 return 0; 94 }
以上是关于TCP编程实现LINUX平台文件传输工程的主要内容,如果未能解决你的问题,请参考以下文章