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