#include <cassert>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
//---------------------------------------------------------------------------
///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExists(const std::string& filename)
{
std::fstream f;
f.open(filename.c_str(),std::ios::in);
return f.is_open();
}
//---------------------------------------------------------------------------
///FileToVector reads a file and converts it to a std::vector<std::string>
///From http://www.richelbilderbeek.nl/CppFileToVector.htm
const std::vector<std::string> FileToVector(const std::string& filename)
{
assert(FileExists(filename)==true);
std::vector<std::string> v;
std::ifstream in(filename.c_str());
std::string s;
for (int i=0; !in.eof(); ++i)
{
std::getline(in,s);
v.push_back(s);
}
return v;
}
//---------------------------------------------------------------------------
///FindIpAddress finds a single IP address in a std::string
const std::string FindIpAddress(const std::string& s)
{
const boost::regex r("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
boost::match_results<std::string::const_iterator> what;
if (boost::regex_search( s.begin(), s.end(), what, r))
return what.str();
else
return std::string();
}
//---------------------------------------------------------------------------
///GetIpAddress finds this computer's IP address
///From http://www.richelbilderbeek.nl/CppGetIpAddress.htm
const std::string GetIpAddress()
{
std::system("snarf www.cmyip.com - > tmp.txt");
const std::vector<std::string> v(FileToVector("tmp.txt"));
BOOST_FOREACH(const std::string& s,v)
{
if (s.size() > 7 && s.substr(0,7) == "<title>")
return FindIpAddress(s);
}
return std::string();
}
//---------------------------------------------------------------------------
int main()
{
std::cout << GetIpAddress() << '\n';
}
//---------------------------------------------------------------------------
|