linux获取局域网、公网IP地址以及主机名

2 篇文章 0 订阅
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);
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值