网络编程 文件传输
1,文件发送端
2,文件接收端
文件发送端:
#include#include #include #include #include //结构体addrinfo, in_addr#include #include #include #include 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#include #include #include #include //结构体addrinfo, in_addr#include #include #include #include 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