int IsLANIP(unsigned int nIP)
{
// filter LAN IP's
// -------------------------------------------
// 0.*
// 10.0.0.0 - 10.255.255.255 class A
// 172.16.0.0 - 172.31.255.255 class B
// 192.168.0.0 - 192.168.255.255 class C
unsigned char nFirst = (unsigned char)nIP;
unsigned char nSecond = (unsigned char)(nIP >> 8);
/* check this 1st, because those LANs IPs are mostly spreaded
*/
if (nFirst==192 && nSecond==168)
return 1;
if (nFirst==172 && nSecond>=16 && nSecond<=31)
return 1;
if (nFirst==0 || nFirst==10)
return 1;
if(nFirst==127)
return 1;
if(nFirst==169 && nSecond==254)
return 1;
return 0;
}
void get_server_info(char* public_ip,char* local_ip,char* hostname,size_t hostname_size)
{
struct sockaddr_in *sin = NULL;
struct ifaddrs *ifa = NULL, *ifList;
*public_ip = 0;
*local_ip = 0;
*hostname=0;
gethostname(hostname,hostname_size);
if (getifaddrs(&ifList) < 0)
return;
for (ifa = ifList; ifa != NULL; ifa = ifa->ifa_next)
{
if(ifa->ifa_addr->sa_family == AF_INET)
{
if(strcmp(ifa->ifa_name,"lo")==0){
continue;
}
sin = (struct sockaddr_in *)ifa->ifa_addr;
if(!IsLANIP(sin->sin_addr.s_addr)){
strcpy(public_ip,inet_ntoa(sin->sin_addr));
}
else
strcpy(local_ip,inet_ntoa(sin->sin_addr));
}
}
freeifaddrs(ifList);
}
linux获取局域网、公网IP地址以及主机名
最新推荐文章于 2024-08-15 08:30:00 发布