C++ scan file for ipv4 and dump ipv4 into a new file.
Posted 05-22-2023, 07:26 PM
To scan a file for IPv4 addresses and append them to a new file in C++, you can follow these steps:1. Open the input file using `ifstream` and the output file using `ofstream`.
c++
Code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream input("input.txt");
ofstream output("output.txt", ios::app);
if (!input.is_open()) {
cout << "Error opening input file\n";
return 1;
}
if (!output.is_open()) {
cout << "Error opening output file\n";
return 1;
}
string line;
while (getline(input, line)) {
// process each line
}
input.close();
output.close();
return 0;
}
2. For each line in the input file, you can use a regular expression to find IPv4 addresses using `std::regex`.
c++
Code
#include <regex>
// regular expression to match IPv4 addresses
const regex pattern(R"((\d{1,3}\.){3}\d{1,3})");
while (getline(input, line)) {
smatch matches;
string::const_iterator searchStart(line.cbegin());
while (regex_search(searchStart, line.cend(), matches, pattern)) {
// process each IPv4 address
output << matches[0] << '\n';
searchStart = matches.suffix().first;
}
}
3. In the loop, each matched IPv4 address is appended to the output file.
4. Finally, close the input and output files.
Here's the complete code:
c++
Code
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
using namespace std;
int main() {
ifstream input("input.txt");
ofstream output("output.txt", ios::app);
if (!input.is_open()) {
cout << "Error opening input file\n";
return 1;
}
if (!output.is_open()) {
cout << "Error opening output file\n";
return 1;
}
const regex pattern(R"((\d{1,3}\.){3}\d{1,3})");
string line;
while (getline(input, line)) {
smatch matches;
string::const_iterator searchStart(line.cbegin());
while (regex_search(searchStart, line.cend(), matches, pattern)) {
output << matches[0] << '\n';
searchStart = matches.suffix().first;
}
}
input.close();
output.close();
return 0;
}
If you want you can add too the code and put arguments for the main function
to use the command prompt to insert name of files to scan and the new of the file to append the ip's found.
I am working on this code to add that functionality into it and will also add more code to this to
scan the new file for duplicated ip addresses.
Hope this helps you anyway.
Thanks for taking a look at this.