I want to code this kind of program so that I can merge it with my ip handler program that adds ip addresses onto a database. My question now is how can I get the external ip address of the computer and not the router nor the ISP provider or something else. It is worth noting that I'm on Visual Studio 2017. Please note I'm using this for learning purposes and not for malicious purposes. Here's my revised version of the code:
IpHandler.cpp
#include "stdafx.h"
#include "IpHandler.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _WINSOCK_DEPCRECATED
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <vector>
#include <locale>
#include <sstream>
#pragma comment(lib,"ws2_32.lib")
using std::cout; using std::locale; using std::istringstream;
string IpHandler::website_HTML = "";
char IpHandler::buffer[10000];
IpHandler::IpHandler(){ }
void IpHandler::get_Website(string url) {
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
struct hostent *host;
string get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
return;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
host = gethostbyname(url.c_str());
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
cout << "Could not connect";
system("pause");
return;
}
send(Socket, get_http.c_str(), strlen(get_http.c_str()), 0);
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
website_HTML += buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
}
string IpHandler::GetExternalIp() {
locale local;
char lineBuffer[200][80] = { ' ' };
char ip_address[16];
int lineIndex = 0;
get_Website("api.ipify.org");
for (int i = 0; i < website_HTML.length(); ++i) { website_HTML[i] = tolower(website_HTML[i], local); }
istringstream ss(website_HTML);
string stoken;
while (getline(ss, stoken, '\n')) {
strcpy_s(lineBuffer[lineIndex], stoken.c_str());
int dot = 0;
for (int ii = 0; ii< strlen(lineBuffer[lineIndex]); ii++) {
if (lineBuffer[lineIndex][ii] == '.') dot++;
if (dot >= 3) {
dot = 0;
strcpy_s(ip_address, lineBuffer[lineIndex]);
}
}
lineIndex++;
}
return ip_address;
}
IpHandler::~IpHandler()
{
}
IpHandler.h
#pragma once
#include <string>
using std::string;
class IpHandler
{
static string website_HTML;
static void get_Website(string url);
static char buffer[10000];
public:
IpHandler();
static string GetExternalIp();
~IpHandler();
};