網路編程 文件傳輸 1,文件發送端 2,文件接收端 文件發送端: "github源代碼" 接收端的執行方式: c/c++ 學習互助QQ群:877684253 本人微信:xiaoshitou5854 ...
網路編程 文件傳輸
1,文件發送端
2,文件接收端
文件發送端:
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>//結構體addrinfo, in_addr
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char* argv[]){
char* service = "12345";
addrinfo hints, *res0, *res;
int err;
int sock;
int fd;
char buf[65536];
int n, ret;
if(argc != 3){return 1;}
fd = open(argv[2], O_RDONLY);
if(fd < 0){
perror("open");
return 1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = PF_UNSPEC;//既適應IPv4又適應IPv6
if((err = getaddrinfo(argv[1], service, &hints, &res0)) != 0){
printf("error %d:%s\n", err, gai_strerror(err));
return 1;
}
for(res = res0; res != NULL; res = res->ai_next){
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sock < 0){continue;}
if(connect(sock, res->ai_addr, res->ai_addrlen) != 0){
close(sock);
continue;
}
break;
}
freeaddrinfo(res0);
if(res == NULL){
printf("failed\n");
return 1;
}
while((n = read(fd, buf, sizeof(buf))) > 0){
ret = write(sock, buf, n);
if(ret < 1){
perror("write");
break;
}
}
close(sock);
return 0;
}
發送端的執行方式:
./a.out 127.0.0.1 text.txt
文件接收端
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>//結構體addrinfo, in_addr
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int sock0;
sockaddr_in client;
socklen_t len;
int sock;
addrinfo hints, *res;
int err;
int fd;
int n, ret;
char buf[65536];
if(argc != 2){return 1;}
fd = open(argv[1], O_WRONLY | O_CREAT, 0600);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
err = getaddrinfo(NULL, "12345", &hints, &res);
if(err != 0){
printf("error %d:%s\n", err, gai_strerror(err));
return 1;
}
sock0 = socket(res->ai_family, res->ai_socktype, 0);
bind(sock0, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
listen(sock0, 5);
len = sizeof(client);
sock = accept(sock0, (sockaddr*)&client, &len);
while((n = read(sock, buf, sizeof(buf))) > 0){
ret = write(fd, buf, n);
}
close(sock);
close(sock0);
return 0;
}
接收端的執行方式:
./a.out textsave.txt