C实用接口--判断ip是否在某个子网内

应用场景

某些环境下需要用户填入ip,但此时该ip可能和其他场景的子网会冲突,导致不可预期的问题,需要判断ip是否合法。

实际案例

路由器设备中,VPN功能需要填写远端子网掩码,然后路由器设备本身又可以修改lan桥ip地址,此时两个子网不能冲突,需要分别判断,否则报文流路会异常

代码

#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>

static int is_ip_in_subnet(const char *ip_str, const char *subnet_str)
{
	struct in_addr ip_addr, subnet_addr, subnet_mask;
	char subnet_ip[INET_ADDRSTRLEN];
	int prefix_len;

	if (inet_pton(AF_INET, ip_str, &ip_addr) != 1) {
		fprintf(stderr, "Invalid IP address: %s\n", ip_str);
		return 0;
	}

	if (sscanf(subnet_str, "%63[^/]/%d", subnet_ip, &prefix_len) != 2) {
		fprintf(stderr, "Invalid subnet format: %s\n", subnet_str);
		return 0;
	}
	if (inet_pton(AF_INET, subnet_ip, &subnet_addr) != 1) {
		fprintf(stderr, "Invalid subnet IP: %s\n", subnet_ip);
		return 0;
	}

	subnet_mask.s_addr = htonl(~((1 << (32 - prefix_len)) - 1));

	return ((ip_addr.s_addr & subnet_mask.s_addr) == (subnet_addr.s_addr & subnet_mask.s_addr));
}

int main(void) { //IP  192.168.1.1   Subnet 192.168.1.0/24
		if (is_ip_in_subnet("192.168.1.1", "192.168.1.0/24")) {
		    printf("IP address is in the subnet \n");
		    return -1;
		}
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值