#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
}
获取本机IP
最新推荐文章于 2023-12-05 21:36:21 发布
本文介绍了一种跨平台获取服务器IP地址的方法。对于Linux系统,利用网络接口信息来查找非回环地址;对于其他系统,则通过主机名解析来获取IP地址。此方法适用于需要自动配置网络连接的应用场景。
3824

被折叠的 条评论
为什么被折叠?



