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.
Asked
Active
Viewed 3,344 times
4 Answers
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
-
-
isn't this a question about C++ not c# ?? I could contribute an answer in Perl too after all ... – siukurnin Feb 06 '09 at 14:17
-
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 Feb 06 '09 at 14:25
-
I was assuming this was managed C++, since it was not specified – Chris Ballance Feb 06 '09 at 14:59
0
Does it really have to be C++? Regular expressions and grep
are your friends!

kquinn
- 10,433
- 4
- 35
- 35
-
Perhaps he wants to make connections to the IP addresses that he is reading in. – dreamlax Feb 06 '09 at 02:14