tags:

views:

1099

answers:

4

Hi,

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. Can you please help me out?

+5  A: 

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

ceretullis
+2  A: 

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
A: 

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

kquinn
Perhaps he wants to make connections to the IP addresses that he is reading in.
dreamlax
+1  A: 

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
Where does System::Text::RegularExpressions come from?
ypnos
It's part of the CLR
Chris Ballance
isn't this a question about C++ not c# ?? I could contribute an answer in Perl too after all ...
siukurnin
I think this is managed C++ not C#. Either way it's hard to know what the author wanted. This seems like it should help though.
Sean
I was assuming this was managed C++, since it was not specified
Chris Ballance