【问题标题】:How to read from a binary file in network byte order and create a struct sockaddr_in in c如何以网络字节顺序从二进制文件中读取并在 c 中创建 struct sockaddr_in
【发布时间】:2020-09-07 14:52:49
【问题描述】:

所以我试图读取一个二进制文件,其中字节按网络字节顺序排列。在文件中,它们包含为套接字编程创建 struct sockaddr_in 所需的信息。这些文件的排列方式是,前 4 个字节代表 IPv4 地址,接下来的 2 个字节代表端口号(没有分隔符或终止符)。 现在,我的麻烦在于试图找到一种读取文件的方法。目前我正在逐字节读取文件并将前 4 个字节存储在 4 元素数组中,然后将接下来的 2 个字节存储在 2 元素数组中。但是,我不确定如何将其转换为结构所需的适当值。谁能为我的实施提供一些建议,是否正确?

  uint64_t address[4]; // a 4 element array
  uint64_t port[2];

  // indexes to help assign bytes to above arrays 
  index1 = 0;
  index2 = 0;

  FILE* ptr = fopen(filename, "rb");
  if (ptr == NULL) {
    perror("Cannot open file.");
    return;
  }

  fseek(ptr, 0, SEEK_END);
  file_len = ftell(ptr); // finding the 
  rewind(ptr);

  for (int i = 0; i < file_len; i++) {
    if (i < 4) {
      fread(address[index1], 1, 1, ptr);
      index1++;
    }
    else if (i >= 4 && i < 6) {

      fread(port[index2], 1, 1, ptr);
      index2++;
    }
  }

  struct sockaddr_in socket_address;
  socket_address.sin_family = AF_INET;

  // i want to assign the 'address' array to this 
  // variable but I'm unsure how to do so
  socket_address.sin_addr.s_addr = // address array;

  // similarly I want to assign the port array to this variable 
  socket_address.sin_port = // port array obtained from above



【问题讨论】:

    标签: c sockets network-programming byte port


    【解决方案1】:

    查看此链接C program to check little vs. big endian 以获取有关指针在小端和大端系统中如何准确指向的信息,您的代码应该是这样的

    用于读取 IPv4

    unsigned int ip; // assuming 4 bytes
    read(fileno(fp), (void*)&ip, 4);   // This would be sufficient for big-endian systems
    ip = ntohl(ip)  // if your system is little-endian
    

    对于端口

    u_int16_t port; 
    read(fileno(fp), (void*)&port, 2);   // This would be sufficient for big-endian systems
    port = ntohs(port)  // if your system is little-endian
    

    现在变量是系统的原生形式。分配给struct sockaddr_in 时,您需要将它们转换为网络字节顺序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2022-01-17
      • 2012-07-11
      相关资源
      最近更新 更多