Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <stdlib.h> /* atoi */
- #include <sstream>
- using namespace std;
- string int2string(int num)
- {
- ostringstream os;
- os << num;
- return os.str();
- }
- string ip2string(vector<short> ip)
- {
- string ret;
- for (vector<short>::iterator i = ip.begin(); i != ip.end(); ++i)
- ret += (i != ip.begin() ? "." : "") + int2string(*i);
- return ret;
- }
- string ip2string(vector<unsigned char> ip)
- {
- string ret;
- for (vector<unsigned char>::iterator i = ip.begin(); i != ip.end(); ++i)
- ret += (i != ip.begin() ? "." : "") + int2string(*i);
- return ret;
- }
- int IPv4Loopup(const vector<vector<unsigned char > >* addrList, vector<vector<unsigned char > >* matches, string* mask)
- {
- if (!addrList) // no list to search
- return -1;
- if (!matches) // no place to store matches
- return -1;
- if (mask->length() == 0) // no mask
- return -1;
- // parse the mask into something we can use
- vector<short> useableMask;
- size_t pos = 0;
- size_t posEnd = 0;
- while (posEnd != string::npos)
- {
- posEnd = mask->find(".", pos);
- string byte = mask->substr(pos, posEnd-pos);
- if (byte == "*")
- useableMask.push_back(-1);
- else
- useableMask.push_back(atoi(byte.c_str()));
- pos = posEnd + 1;
- }
- // search through addrList for ones matching mask, if so, put it in matches
- // return the number of matches
- int numFound = 0;
- for (vector<vector<unsigned char> >::const_iterator it = addrList->begin(); it != addrList->end(); ++it)
- {
- vector<unsigned char> ip = *it;
- bool match = true;
- for (int i = 0; i < ip.size(); ++i)
- {
- if (useableMask[i] == -1) // wild card, match away
- continue;
- if (useableMask[i] != ip[i]) // no match
- {
- match = false;
- break;
- }
- }
- if (match)
- {
- numFound++;
- matches->push_back(ip);
- }
- }
- return numFound;
- }
- int main()
- {
- vector<vector<unsigned char > > list;
- vector<vector<unsigned char > > matches;
- vector<unsigned char> tmp;
- tmp.push_back(192);
- tmp.push_back(168);
- tmp.push_back(100);
- tmp.push_back(101);
- list.push_back(tmp);
- tmp.clear();
- tmp.push_back(192);
- tmp.push_back(168);
- tmp.push_back(100);
- tmp.push_back(102);
- list.push_back(tmp);
- tmp.clear();
- tmp.push_back(127);
- tmp.push_back(0);
- tmp.push_back(0);
- tmp.push_back(1);
- list.push_back(tmp);
- string mask = "192.168.*.*";
- cout << "Found " << IPv4Loopup(&list, &matches, &mask) << " matches" << endl;
- cout << "Mask: " << mask << endl;
- cout << "Matches: ";
- for (vector<vector<unsigned char> >::iterator i = matches.begin(); i != matches.end(); ++i)
- {
- cout << ip2string(*i) << " ";
- }
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement