windows+linux获得本地ip(内网ip)

#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
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值