VC++ 获得本地中指定网段的IP

从网上借鉴了方法,实现获得本机的众多IP中,指定某个网段的IP地址,这里是指局域网环境下,偷懒的方式,只比较了IP地址的第三个数字,严谨的来说,需要根据子网掩码来获得网段地址,进而逐个比较的。

byte charToInt(char * str, int start_idx, int end_idx)
{
    int a = 0, i;
    for (i = start_idx; i <= end_idx; ++i)
    {
        a = a * 10 + (str[i] - '0');
    }

    return (byte)a;
}

int CutIPtoInt(char * ip, int iCutSet)
{
    int start = 0, i = 0, ret = 0, ia = 0;
    int shift_factor = 1; // 
    char c;
    while (c = ip[i])
    {
        if (c == '.')
        {
            ia = charToInt(ip, start, i - 1);
            if (shift_factor == iCutSet)
                return ia;
            ++shift_factor;
            start = i + 1;
        }
        i++;
    }
    return ret;
}

bool IsSameNetSegment(char* pIpA, char* pIpB)
{
    bool bRtn = false;
    int iIpA = CutIPtoInt(pIpA, 3);
    if (iIpA == CutIPtoInt(pIpB, 3))
        bRtn = true;
    return bRtn;
}

char* GetTheSameNetSegmentIPaddr(char * pTargetIP)
{
    char szHost[256] = "";
    char szIp[256] = "";
    //取得本地主机名
    ::gethostname(szHost, 256);
    //通过主机名得到地址信息
    hostent *pHost = ::gethostbyname(szHost);
    //char* pTargetIP = "192.168.5.30";
    in_addr addr;
    for (int i = 0;; i++)
    {
        //p指向一个32位的IP地址
        char *p = pHost->h_addr_list[i];
        if (p == NULL)
        {
            break;
        }
        memcpy(&addr.S_un.S_addr, p, pHost->h_length);
        char *szIpTemp = ::inet_ntoa(addr);
        if (IsSameNetSegment(pTargetIP, szIpTemp))
        {
            strcpy_s(szIp, szIpTemp);
            return szIp;
        }
    }
    return "127.0.0.1";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值