C ++如何获取我的电脑的外部IP地址?

时间:2018-01-02 10:25:42

标签: c++ visual-studio

我想编写这种程序代码,以便我可以将它与我的ip处理程序合并,该程序将ip地址添加到数据库中。我现在的问题是如何获取计算机的外部IP地址,而不是路由器,ISP提供商或其他东西。值得注意的是,我在Visual Studio 2017上。请注意我将其用于学习目的,而不是用于恶意目的。这是我修改后的代码版本:

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();
};

0 个答案:

没有答案