#if defined(__linux__)
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <list>
#include <string>
#include <iostream>
using namespace std;
int get_ip_linux(int ipv4_6, std::list<std::string>& out_list_ip) {
int ret_val = 0;
struct ifaddrs * ifAddrStruct = NULL;
void * tmpAddrPtr = NULL;
ret_val = getifaddrs(&ifAddrStruct);
if (0 != ret_val) {
ret_val = errno;
return ret_val;
}
std::string str_ipvX;
int padress_buf_len = 0;
char addressBuffer[INET6_ADDRSTRLEN] = { 0 };
if (AF_INET6 == ipv4_6)
padress_buf_len = INET6_ADDRSTRLEN;
else
padress_buf_len = INET_ADDRSTRLEN;
while (NULL != ifAddrStruct) {
if (ipv4_6 == ifAddrStruct->ifa_addr->sa_family) {
// is a valid IP4 Address
tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
inet_ntop(ipv4_6, tmpAddrPtr, addressBuffer, padress_buf_len);
str_ipvX = std::string(addressBuffer);
out_list_ip.push_back(str_ipvX);
memset(addressBuffer, 0, padress_buf_len);
}
ifAddrStruct = ifAddrStruct->ifa_next;
}
return ret_val;
}
int get_ipv4_linux(std::list<std::string>& out_list_ip4) {
return get_ip_linux(AF_INET, out_list_ip4);
}
#endif
std::string HttpRequestHelper::GetLocalIpAddress()
{
#ifdef WIN32
string localIP = "";
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData) != 0)
return "";
char local[255] = { 0 };
gethostname(local, sizeof(local));
hostent* ph = gethostbyname(local);
if (ph == NULL)
return "";
for (int i = 0;; i++)
{
localIP = inet_ntoa(*(IN_ADDR*)ph->h_addr_list[i]);
std::vector<long long> vecRet;
Common::SplitString2Int(localIP, ".", vecRet);
if (vecRet[0] == 192 && vecRet[1] == 168 && vecRet[2] == 0) //获得192.168.0.X的ip
break;
if (ph->h_addr_list[i] + ph->h_length >= ph->h_name)
break;
}
WSACleanup();
return localIP;
#else
std::list<std::string> ipv4;
int ret_val = get_ipv4_linux(ipv4);
if (0 != ret_val) {
return "127.0.0.1";
}
else {
int index = 0;
for (auto item : ipv4) {
++index;
cout << ", ipv4 = " << item.c_str() << endl;
if(strcmp(item.c_str(),"127.0.0.1") == 0)
continue;
return item;
}
}
return "127.0.0.1"; // 如果没有找到,返回本地回环地址
#endif
}
windows+linux获得本地ip(内网ip)
于 2024-08-08 16:40:36 首次发布