1

So I'm trying to read a binary file where the bytes are arranged in network byte order. In the files they contain the information needed to create a struct sockaddr_in for socket programming. The files are arranged such that the first 4 bytes represent the IPv4 address and the next 2 bytes represent the port number (no deliminators or terminators). Now, where my trouble lies is trying to find a way to read the file. Currently I'm reading the file byte by byte and storing the first 4 bytes in a 4 element array and then the next 2 bytes in a 2 element array. However, I'm unsure as to how I can convert it to the appropriate values needed for the struct. Could anyone please provide me some advice for my implementation, and if it is correct or not?

  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



1 Answers1

0

Check this link C program to check little vs. big endian for the information on how exactly the pointers are pointed in little-endian and big-endian systems, from that your code should be something like this

for reading 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

For port

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

Now the variables are in native form of the system. When assigning to struct sockaddr_in you need to convert them to network byte order

m0hithreddy
  • 1,752
  • 1
  • 10
  • 17