ip in ip-range

190 篇文章 1 订阅
/*
*ip range test
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


unsigned long ip2ulong(char *ip)
{
    unsigned u1, u2, u3, u4;
    return sscanf(ip, "%u.%u.%u.%u", &u1, &u2, &u3, &u4) == 4 &&
           u1 <= 255 && u2 <= 255 && u3 <= 255 && u4 <= 255
           ? u1*256*256*256 + u2*256*256 + u3*256 + u4 : 0;



int main(int argc, char *argv[])
{
char *ip_str="192.168.20.1/16";
char ip[20];
char str_mask[3];
char *p=NULL;


unsigned long int mask;
bzero(ip, sizeof(ip));
bzero(str_mask, sizeof(str_mask));
if((p=strchr(ip_str,'/'))!=NULL) {
strncpy(ip, ip_str, p-ip_str);
strncpy(str_mask, p+1, sizeof(str_mask));
}
printf("%d mask\n", atoi(str_mask));
mask = ~((1 << (32 - atoi(str_mask))) - 1);

unsigned long startIP=ip2ulong(ip);
printf("%lu ip\n", startIP);
startIP = startIP & mask;
unsigned long endIP  = (startIP & mask) | ~mask;
printf("%lu %lu\n", startIP, endIP);
return 0;

}


The steps would go like this for a network/maskBits,

You compute the mask in one of these two ways,

mask = ~((1 << (32 - maskBits)) - 1) // or,
mask = ~(0xFFFFFFFF >> maskBits)

then the range is,

StartIP = network 
EndIP   = network | ~mask

More precisely,

StartIP = network & mask
EndIP   = (network & mask) | ~mask

Where,

  • << is bitwise left shift (without rollover)
  • & is bitwise AND,
  • | is bitwise OR, and
  • ~ is bitwise INVERT.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值