|
在ACE中怎么得到机器的机器名或机器的IP
-------------------------------------------------------
ACE_INET_Addr * plocal_addrs = NULL;
int nRead = ACE::get_ip_interfaces(addr_count,plocal_addrs);
ACE_OS::hostname()
#include <ace/OS.h>
int main(int argc, char *argv[])
{
//获取本机主机名
char hostname[20];
ACE_OS::hostname(hostname,20);
struct hostent *hptr;
//调用gethostbyname()获取主机地址信息
if( (hptr = ACE_OS::gethostbyname(hostname) ) == NULL )
{
printf("gethostbyname error for host:%s\n", hostname);
return 0; //如果调用gethostbyname发生错误,返回
}
//将主机的规范名打出来
printf("hostname:%s\n",hptr->h_name);
char **pptr;
//主机可能有多个别名,将所有别名分别打出来
for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
printf(" alias:%s\n",*pptr);
char ip[32];
//根据地址类型,将地址打出来
switch(hptr->h_addrtype)
{
case AF_INET:
case AF_INET6:
pptr=hptr->h_addr_list;
//将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数
for(;*pptr!=NULL;pptr++)
printf("address:%s\n", ACE_OS::inet_ntop(hptr->h_addrtype, *pptr, ip, sizeof(ip)));
break;
default:
printf("unknown address type\n");
break;
}
return 0;
}
#include <ace/os.h>
#include <ace/INET_Addr.h>
void print_all_interfaces()
{
ACE_INET_Addr* addr_array;
size_t count = 0;
if (ACE::get_ip_interfaces(count, addr_array) != 0)
return;
char address[INET6_ADDRSTRLEN];//可以装下IPv6地址
ACE_INET_Addr* addr_array2 = addr_array;
while (count--)
{
addr_array2->addr_to_string(address, sizeof (address));
ACE_OS::printf("%s\n", address);
++addr_array2;
}
delete[] addr_array;//记得要delete[] addr_array;
}
int ACE_TMAIN(int, ACE_TCHAR *[])
{
print_all_interfaces();
system("PAUSE");
return 0;
} |
|