#include <iostream>
#include <string>
#include <vector>
#include "tcp_stream.h"

using namespace std;
using namespace net_tools;

typedef vector< string > args_type;

class whatismyip {
public:
   bool read_line(tcp_stream & tcp, string & line) {
      bool ret = false;
      char ch;
      line = "";
      ch = tcp.get();
      while(tcp) {
         ret = true;
         line += ch;
         if(line.size() >= 8192) break;
         if(ch == '\n') break;
         ch = tcp.get();
      }
      return ret;
   }
   int run(const args_type & args) {  
      int rc = 0;
      tcp_stream tcp("checkip.dyndns.org", 80);
      if(tcp) {
         tcp << "GET / HTTP/1.0\r\n\r\n";
         char ch;
         string line;
         int count = 0;
         while(read_line(tcp,line)) {
            count++;
            if(count >= 100) break;
            if(line == "\r\n") break;
         }
         ch = tcp.get();
         string buffer;
         while(tcp) {
            buffer += ch;
            if(buffer.size() >= 8192) break;
            ch = tcp.get();
         }
         tcp.close();
         string::size_type p = buffer.find("Current IP Address: ");
         if(p != string::npos) {
            buffer = buffer.substr(p+20);
            p = buffer.find("<");
            if(p != string::npos) {
               buffer = buffer.substr(0,p);
               cout << buffer << endl;
            }
         }
      }
      return rc;
   }
};

int
main(int argc, char* argv[])
{
   WORD wVersionRequested;
   WSADATA wsaData;
   wVersionRequested = MAKEWORD(2, 2);
   WSAStartup(wVersionRequested, &wsaData);
   whatismyip getip;
   args_type args;
   getip.run(args);
   WSACleanup();
   return 0;
}
