0

I need to write a program to scan a text file and retrieve all ip addresses (of the format 256.256.256.256) in the file.

tshepang
  • 12,111
  • 21
  • 91
  • 136

4 Answers4

5

You could write a BNF using Boost::spirit or create a regular expression to find the IP addresses using Boost::regex

oz10
  • 153,307
  • 27
  • 93
  • 128
2

Maybe you should try using regular expressions? You could read the file in, scanning it line by line maybe, and then use a regular expression on the line to extract the IP addresses.

If the file contains only IP addresses and no other text, it might be easier to use scanf, with "%hhu.%hhu.%hhu.%hhu" as the format string.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
1

This Regular Expression will do the trick:

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

Modify this code for your specific needs:

using namespace System::Text::RegularExpressions;
void doTheMatch( String^ inputString, String^ filter )
{
    Console::WriteLine( "original string:  {0}", inputString );
    Console::WriteLine( "attempt to match: {0}", filter );

    Regex^ regex = gcnew Regex( filter );
    Match^ match = regex->Match( inputString );

    if ( ! match->Success )
    {
        Console::WriteLine( 
            "Sorry, no match of {0} in {1}", filter, inputString );
        return;
    }

    for ( ; match->Success; match = match->NextMatch() )
    {
        Console.WriteLine( 
            "The characters {0} match beginning at position {1}",  
            match->ToString(), match->Index );
    }
}
Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
0

Does it really have to be C++? Regular expressions and grep are your friends!

kquinn
  • 10,433
  • 4
  • 35
  • 35