THE DOCTOR
THE DOCTOR

Reputation: 4555

Parsing and Comparing IP Addresses In C++

I am trying to write a utility that does the following:

  1. Reads a file to parse IP addresses
  2. Compare IP addresses that are parsed from the file to a master list to find the missing ones
  3. Output the IP addresses that are missing

What would be a good way to implement items 2 and 3? So far, I am doing the following to get a total count of the number of IP addreses I have parsed from the file:

if (strstr (line, "IP_Address=128.10.")) {
    fprintf(ofp, "%s\n", line);
    ip_addresses++; // counter for IP addresses starting with 128.10
}

How should I perform the comparison of the parsed IP addresses to my master list and how can I detect the missing ones when I check against my list of IPs?

Upvotes: 1

Views: 2067

Answers (2)

michelangelo
michelangelo

Reputation: 1

First, convert the addresses to unsigned integers. Assuming that you keep the parsed addresses as arrays of ints, the code could look like this:

//  If ip is 195.102.45.203, then unsigned int IP = {195, 102, 45, 203};
unsigned int identifier = 0;
identifier = ((IP[0]*255 + IP[1])*255 + IP[2])*255 + IP[3];

Insert all identifiers to some vector, sort it and do the same with addresses from master list. Then check if there are any missing ones.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490008

I would convert each IP address to a 32-bit unsigned integer when reading (at least assuming IPv4, which seems to be the case).

Then I'd insert those into vector and sort them. Do the same with your master list, and use std::set_difference to find the difference.

Upvotes: 3

Related Questions