欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 网络编程 文件传输

程序员文章站 2022-07-08 19:59:42
网络编程 文件传输 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

c/c++ 学习互助qq群:877684253

c/c++ 网络编程 文件传输

本人微信:xiaoshitou5854