#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
最新推荐文章于 2022-08-07 15:38:19 发布