![enter image description here](https://i.stack.imgur.com/S2Kxi.jpg)
Один из способов получения внешнего ip на языке c / c ++ - использовать API-интерфейс для веб-адреса, загрузить веб-страницу, содержащую ваш IP-адрес, в массив char и извлечь IP-адрес из источника HTML. Вот некоторый код winsock, чтобы продемонстрировать это. он использует http://api.ipify.org/ онлайн веб-API.
//
// Winsock get external ip address from website api at api.ipify.org
// api.ipify.org
//
#include <string.h>
#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>
#include <locale>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
string website_HTML;
locale local;
char ipaddress[16];
int ic=0;
void get_Website(char *url );
char mystring[] = " ";
char seps[] = " ,\t\n";
char *token;
char lineBuffer[200][80] ={' '};
char buffer[10000];
char ip_address[16];
int i = 0, bufLen=0, j=0,lineCount=0;
int lineIndex=0, posIndex=0;
int main( void ){
SYSTEMTIME st;
GetLocalTime(&st);
char *today = new char[32];
memset(today,' ', sizeof(today) );
sprintf(today,"%d-%d-%d", st.wYear , st.wMonth , st.wDay);
memset(buffer,'\0',sizeof(buffer));
get_Website("api.ipify.org" );
for (size_t i=0; i<website_HTML.length(); ++i) website_HTML[i]= tolower(website_HTML[i],local);
token = strtok( buffer , seps );
while( token != NULL ){
strcpy(lineBuffer[lineIndex],token);
int dot=0;
for (int ii=0; ii< strlen( lineBuffer[lineIndex] ); ii++ ){
if (lineBuffer[lineIndex][ii] == '.') dot++;
if (dot>=3){
dot=0;
strcpy(ip_address,lineBuffer[lineIndex]);
}
}
token = strtok( NULL, seps );
lineIndex++;
}
cout<<"Your IP Address is "<< ip_address<<" \n\n";
return 0;
}
void get_Website(char *url ){
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
char *get_http= new char[256];
memset(get_http,' ', sizeof(get_http) );
strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
strcat(get_http,url);
strcat(get_http,"\r\nConnection: close\r\n\r\n");
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(url);
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 1;
}
send(Socket,get_http, strlen(get_http),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();
delete[] get_http;
}