【发布时间】: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