获取本机IP

本文介绍了一种跨平台获取服务器IP地址的方法。对于Linux系统,利用网络接口信息来查找非回环地址;对于其他系统,则通过主机名解析来获取IP地址。此方法适用于需要自动配置网络连接的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <Ice/Ice.h>

#ifdef __linux

#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <string.h> 

#endif

using namespace std;

	string getServerAddress()
	{
#ifdef __linux
		struct ifaddrs * ifAddrStruct=NULL;
		void * tmpAddrPtr=NULL;

		getifaddrs(&ifAddrStruct);
		string ipInfo;
		while (ifAddrStruct!=NULL) 
		{
			if (ifAddrStruct->ifa_addr->sa_family==AF_INET) 
			{ // check it is IP4
				tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
				char addressBuffer[INET_ADDRSTRLEN];
				inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
				if (strcmp(addressBuffer, "127.0.0.1") != 0 && strcmp(addressBuffer, "::") != 0)
				{
					ipInfo = addressBuffer;
				}
			} 
			ifAddrStruct=ifAddrStruct->ifa_next;
		}
		return ipInfo;
#else
		char buff[20];
		gethostname(buff, sizeof(buff) ); 
		struct hostent *hostaddr=gethostbyname(buff);

		struct in_addr addr;
		memcpy(&addr.s_addr, hostaddr->h_addr_list[0], sizeof(addr.s_addr));
		return inet_ntoa(addr);
#endif
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值