Server-side code
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/inch.h>9#include <arpa/inet.h>Ten One #defineMAXLINE 1024 A - voidUsageChar*command) - { theprintf"Usage:%s portnum filename\n", command); -Exit0); - } - intMainintargcChar**argv) + { - structsockaddr_in serv_addr; + structsockaddr_in clie_addr; A CharBuf[maxline]; at intsock_id; - intlink_id; - intRecv_len; - intWrite_leng; - intClie_addr_len; -FILE *FP; in - if(ARGC! =3) { toUsage (argv[0]); + } - /*<-----------------------------------------socket---------------------------------------------->*/ the if(sock_id = socket (af_inet, Sock_stream,0)) <0) * { $Perror ("Create Socket failed\n"); Panax NotoginsengExit0); - } the /*<-----------------------------------------bind-------------------------------------------------> */ +memset (&SERV_ADDR,0,sizeof(SERV_ADDR)); Aserv_addr.sin_family =af_inet; theServ_addr.sin_port = htons (Atoi (argv[1])); +SERV_ADDR.SIN_ADDR.S_ADDR =htonl (Inaddr_any); - $ if(Bind (sock_id, (structSOCKADDR *) &serv_addr,sizeof(SERV_ADDR)) <0 ) $ { -Perror ("Bind Socket failed\n"); -Exit0); the } - /*<-----------------------------------------Listen-----------------------------------------------> */Wuyi if(-1= = Listen (sock_id,Ten)) the { -Perror ("Listen Socket failed\n"); WuExit0); - } About /*<-------------------------------------server Receive part---------------------------------->*/ $ while(1) { - if(fp = fopen (argv[2],"W")) ==NULL) - { -Perror ("Open file failed\n"); AExit0); + } theLseek (FP,0, seek_end); -Clie_addr_len =sizeof(CLIE_ADDR); $ /*<-----------------------------------------Accept-----------------------------------------------> */ thelink_id = Accept (sock_id, (structSOCKADDR *) &clie_addr, &Clie_addr_len); the if(-1==link_id) { thePerror ("Accept Socket failed\n"); theExit0); - } in bzero (buf, MAXLINE); the while(Recv_len = recv (link_id, buf, MAXLINE,0)) the { About if(Recv_len <0) the { theprintf"recieve Data from Server failed!\n"); the Break; + } -printf"#"); theWrite_leng = fwrite (buf,sizeof(Char), Recv_len, FP); Bayi if(Write_leng <Recv_len) the { theprintf"Write file failed\n"); - Break; - } the bzero (Buf,maxline); the } theprintf"\nfinish recieve\n"); the fclose (FP); - Close (link_id); the } the Close (sock_id); the return 0; 94}
TCP Programming for Linux platform File transfer engineering