cocos2dx获取本机全部ip地址。。。
使用的是raknet中获取网卡的方式,支持linux,ios,安卓系统。未支持win。 #if defined(ANDROID) void UdpSocket::getHostIpByString( char ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ][ 16 ],unsigned int binaryAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) { struct ifreq ifreqs[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; struct ifconf ifconf; struct in_addr bin_addr;
memset(&ifconf,0,sizeof(ifconf)); ifconf.ifc_buf = (char*) (ifreqs); ifconf.ifc_len = sizeof(ifreqs);
{ // get list of interfaces int sock = socket(AF_INET,SOCK_STREAM,0); if (sock < 0) { perror("Error creating socket"); return; } if ((ioctl(sock,SIOCGIFCONF,(char*) &ifconf )) < 0 ) { perror("Error returned from ioctl(SIOGIFCONF)"); ifconf.ifc_len = 0; } close(sock); }
int idx = 0; int iface_count = ifconf.ifc_len/sizeof(struct ifreq); printf("Interfaces (%d):n",iface_count); for( ; idx < iface_count; idx++) { char ip_addr[ 16/*INET_ADDRSTRLEN */]; struct sockaddr_in *b = (struct sockaddr_in *) &(ifreqs[idx].ifr_addr); const char* host = inet_ntop(AF_INET,& b->sin_addr,ip_addr,sizeof ip_addr); strcpy( ipList[idx],host ); if (inet_aton(host,&bin_addr) == 0) { perror("inet_aton error"); continue; } else { binaryAddresses[idx] = bin_addr.s_addr; } printf("t%-10st%s (%08x)n",ifreqs[idx].ifr_name,ipList[idx],binaryAddresses[idx]); } for ( ; idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ++idx ) { ipList[idx][0]=0; } } #else void UdpSocket::getHostIpByString(char ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ][ 16 ],unsigned int binaryAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]) { struct ifaddrs *ifaddr,*ifa; int family,s; char host[NI_MAXHOST]; struct in_addr linux_in_addr;
if (getifaddrs(&ifaddr) == -1) { printf( "Error getting interface listn"); }
int idx = 0; for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; family = ifa->ifa_addr->sa_family;
if (family == AF_INET) { s = getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host,NI_MAXHOST,NULL, 0,NI_NUMERICHOST); if (s != 0) { printf ("getnameinfo() failed: %sn",gai_strerror(s)); } printf ("IP address: %sn",host); if (strcmp(host,"127.0.0.1")!=0) { strcpy( ipList[ idx ],host ); if (inet_aton(host,&linux_in_addr) == 0) { perror("inet_aton"); } else { binaryAddresses[idx]=linux_in_addr.s_addr; }
idx++; } } }
for ( ; idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ++idx ) { ipList[idx][0]=0; }
freeifaddrs(ifaddr); } #endif (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |