-1

I have a text file containing some IP addresses.

How can I get the IP addresses even if they change places (for example, taking the IP address from the beginning and writing it to the end)

Text example :

"192.168.4.163 - - [22/Dec/2016:22:32:32 +0300] "GET / HTTP/1.1" 200 3279 "-" "w3af.org""
"192.168.4.163 - - [22/Dec/2016:22:32:32 +0300] "GET / HTTP/1.1" 200 3279 "-" "w3af.org""
" - - [22/Dec/2016:22:32:32 +0300] 192.168.4.163 "GET / HTTP/1.1" 200 3279 "-" "w3af.org""

Code part:

    ifstream listfile;
    listfile.open("log.txt");
    ofstream cleanIp;
    cleanIp.open("ipAddress.txt");
    
    ifstream readIp;
    string ipLine;
    readIp.open("ipAddress.txt");
    
    string temp;
    while(listfile>>temp) //get just ips
    {
        cleanIp<<temp<<endl;
        listfile>>temp;
        getline(listfile, temp);
    }
Ken White
  • 123,280
  • 14
  • 225
  • 444
Mehmet
  • 65
  • 1
  • 7
  • A good first step would be to write a parser that finds an IP address in a string. There's nothing in C++ (that I know of) that does this for you. Try creating that, post the code, and we can go from there. – mzimmers Jan 13 '22 at 22:24
  • You could use the regex system with a match of something like `.*(\d+\.\d+\.\d+\.\d+).*`. You might have to play with that a bit. – Joseph Larson Jan 13 '22 at 22:24
  • In your example the IP address is consistently at the beginning. If you want to process IP addresses in different places, you example should provide lines containing IP addresses not at the beginning. – Serge Ballesta Jan 13 '22 at 22:24
  • I tried bu i couldn't implement it, if you have an idea could you share with me @JosephLarson – Mehmet Jan 13 '22 at 22:25
  • 1
    @Mehmet Why don't you share what you tried? And then simplify it. Try to just get the 192 part, for instance. That would be a lot simpler regex. – Joseph Larson Jan 13 '22 at 22:27
  • 2
    Does this answer your question? [Extract IP address from a string using boost regex?](https://stackoverflow.com/questions/5073992/extract-ip-address-from-a-string-using-boost-regex) – Martheen Jan 13 '22 at 22:27
  • You're right, I edited the issue. @Serge Balesta – Mehmet Jan 13 '22 at 22:27

1 Answers1

3

The standard library includes regex.

You could use something close to:

std::string find_ip(const std::string& line) {
    std::regex rx{ "\\d+\\.\\d+\\.\\d+\\.\\d+" };
    std::smatch ip;
    if (std::regex_search(line, ip, rx)) {
        return ip.str();
    }
    return "";
}

Applied to any line from your example, this consistently returns the string 192.168.4.163.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252