socket文件傳輸-接收端
發送端:https://blog.csdn.net/qq_33904382/article/details/104827471
C 使用socket傳輸文件的接收端。主函數也可作爲一般client端的結構。
主函數:
/* read&write */
#include<stdio.h>
/* structure */
#include<sys/types.h>
#include<netinet/in.h>
/* memset */
#include<string.h>
/* fflush */
#include<fcntl.h>
typedef struct sockaddr SA;
const int maxsize=9056;
/* Receive file ans store it */
void cli_do(FILE* inputfd,int sockfd);
int
main(int argc,char* argv[])
{
/* Get a socket */
int serfd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in ser_addr;
/* Init structure of socket */
ser_addr.sin_family = AF_INET;/* net family */
ser_addr.sin_port = htons(13000);/* socket port */
inet_pton(AF_INET,argv[1],&ser_addr.sin_addr);/* Config IP */
/* Connect with socket server */
connect(serfd,(SA*)&ser_addr,sizeof(ser_addr));
/* What really useful */
cli_do(stdin,serfd);
return 0;
}
cli_do: 接收文件並保存到同目錄下的名爲“txt”的文件
void cli_do(FILE* inputfd,int sockfd)
{
FILE* recv = fopen("./txt","ab");/* File ptr for store distination */
int n;/* size of the file */
char sendbuffer[maxsize],recvbuffer[maxsize];/* buffer for recv and send*/
memset(sendbuffer,0,maxsize);memset(recvbuffer,0,maxsize);
/* Read from socket,write into file ./txt */
while((fgets(sendbuffer,maxsize,inputfd))!=NULL){
write(sockfd,sendbuffer,maxsize);
if(n = read(sockfd,recvbuffer,maxsize)>0){
fprintf(recv,"%s",recvbuffer);
fflush(recv);/* carefully for this */
}
}
fclose(recv);/* just for my habit */
}