gpt4 book ai didi

c - 如何以网络字节顺序从二进制文件读取并在C中创建struct sockaddr_in

转载 作者:行者123 更新时间:2023-12-03 12:07:44 28 4
gpt4 key购买 nike

因此,我试图读取二进制文件,其中字节以网络字节顺序排列。在文件中,它们包含为套接字编程创建结构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 program to check little vs. big endian,以获取有关在Little-endian和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

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

关于c - 如何以网络字节顺序从二进制文件读取并在C中创建struct sockaddr_in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61926659/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com