Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

How do I read IP addresses in binary format from files in C++?

How do I read IP addresses in binary format from files in C++?

Clarfication: The file contains 4 bytes of actual binary data. The ones and zeros below in text format are only for illustration purposes!

If I have a binary file that contains bits, which represented as zeros and one would look like: 00000001 00000000 00010011 00000111 00000010 00000000 00010011 00000111 that represents the ip addresses 1.0.19.7 and 2.0.19.7

How do I read the 32-bit values from the binary file and turn them into an unsigned integer?

What is wrong with the code below?

  FILE *myfile = fopen("binaryipfile.bin", "r");    
   unsigned int ip;
     char string[32];
        while (fgets(string, 32, &myfile)) {
        sscanf(string, "%x", &ip);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To read 32 bits from a binary file, just use fread to read into a 32-bit variable. Like

uint32_t address;
fread(&address, sizeof(address), 1, myfile);

You might have to convert the value using htonl if it's stored in a host endianness that differs from network endianness.

Of course, you must first open the file in binary mode:

FILE *myfile = fopen("binaryipfile.bin", "rb");  // Note the use of "rb"

To do in in C++ using the C++ standard stream library, it would be something like

std::ifstream file("binaryipfile.bin", std::ios::in | std::ios::binary);

uint32_t address;
file.read(reinterpret_cast<char*>(&address), sizeof(address));

No matter if you use the C or C++ way, if you have multiple addresses then read in a loop, possibly putting the addresses into a std::vector. This can be done much simpler if using the C++ function std::copy function paired with std::istreambuf_iterator and std::back_inserter:

std::vector<uint32_t> addresses;
std::copy(std::istreambuf_iterator<uint32_t>(file),
          std::istreambuf_iterator<uint32_t>(),
          std::back_inserter(addresses));

After this the vector addresses will contain all 4-byte values read from the file. If not all of the file contains addresses, you could use std::copy_n instead.

You should also have some error checking, which I left out of my examples to keep them simple.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...