首页 > 系统相关 >Linux C语言 检测IP冲突

Linux C语言 检测IP冲突

时间:2024-01-29 16:24:56浏览次数:24  
标签:ip max min IP mask C语言 Linux net2 net1

分析一个基于C语言实现的IP冲突检测工具。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <getopt.h>
#include <arpa/inet.h>

#define dbg(fmt, args...) printf("\033[1m[ %s ] %03d: "fmt"\033[0m\n\r", __FUNCTION__, __LINE__, ##args)

#define IP_STR_LEN      (16)

typedef struct _NET_ {
    unsigned int ip;
    unsigned int mask;
} NET;

static int debug_on = 0;

static void usage(const char *program)
{
    if (NULL == program) {
        return;
    }

	printf("usage: %s [OPTION], check the ip1/mask1 and ip2/mask2 has conflict or not.\n"
            "\n"
			"  -h, --help\n      print this message\n"
			"  -d, --debug\n     print more message for debug\n"
			"  -i, --ip1         the first ip to check\n"
			"  -m, --mask1       the mask of first ip\n"
			"  -I, --ip2         the second ip to check\n"
			"  -M, --mask2       the mask of second ip\n",
            program);

    return;
}

static unsigned int mask_str_to_val(const char *mask)
{
    unsigned int a, b, c, d;
    if (sscanf(mask, "%u.%u.%u.%u", &a, &b, &c, &d) != 4) {
        dbg("invalid mask:%s", mask);
        return 0;
    }

    /*dbg("%u.%u.%u.%u", a, b, c, d);*/
    return (a << 24) + (b << 16) + (c << 8) + (d);
}

static unsigned int ip_str_to_val(const char *ip)
{
    struct in_addr s;
    if (!ip) {
        return 0;
    }

    inet_pton(AF_INET, ip, (void *)&s);
    return (unsigned int)ntohl(s.s_addr);
}

static int process_options(int argc, char * argv[], NET *net1, NET *net2)
{
    int c = 0;
    int option_index = 0;
    char ip_str[IP_STR_LEN] = {0};
    char mask_str[IP_STR_LEN] = {0};

    static const char *short_options = "hi:m:I:M:d";
    static const struct option long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"debug", no_argument, 0, 'd'},
        {"ip1", no_argument, 0, 'i'},
        {"mask1", no_argument, 0, 'm'},
        {"ip2", no_argument, 0, 'I'},
        {"mask2", no_argument, 0, 'M'},
        {0,0,0,0},
    };

    for (;;) {
		c = getopt_long(argc, argv, short_options,
				long_options, &option_index);

		if (c == EOF) {
			break;
		}

        switch (c) {
        case 'h':
            usage(argv[0]);
			exit(0);
			break;
        case 'd':
            debug_on = 1;
			break;
        case 'i':
            net1->ip = ip_str_to_val(optarg);
			break;
		case 'm':
            net1->mask = mask_str_to_val(optarg);
            break;
		case 'I':
            net2->ip = ip_str_to_val(optarg);
            break;
		case 'M':
            net2->mask = mask_str_to_val(optarg);
            break;
        default:
            dbg("unknown param:%c", c);
            break;
        }
    }
    
    return 0;
}

static int check_conflict(NET *net1, NET *net2)
{
    unsigned int net1_min = net1->ip & net1->mask;
    unsigned int net1_max = net1_min + (~net1->mask);

    if (net1_min > net1_max) {
        dbg("net1_min(%u) > net1_max(%u)", net1_min, net1_max);
        return 1;
    }

    unsigned int net2_min = net2->ip & net2->mask;
    unsigned int net2_max = net2_min + ((~net2->mask));

    if (debug_on) {
        dbg("mask1:%u", ~(net1->mask));
        dbg("mask2:%u", ~(net2->mask));
        dbg("net1_min:%u, net1_max:%u", net1_min, net1_max);
        dbg("net2_min:%u, net2_max:%u", net2_min, net2_max);
    }

    if (net2_min > net2_max) {
        dbg("net2_min(%u) > net2_max(%u)", net2_min, net2_max);
        return 1;
    }

    if (net1_max < net2_min || net1_min > net2_max) {
        return 0;
    } else {
        system("touch /tmp/ip_conflict");
        return 1;
    }
}

int main(int argc, char *argv[])
{
    int conflict = 0;
    NET net1;
    NET net2;

    memset(&net1, 0, sizeof(NET));
    memset(&net2, 0, sizeof(NET));

    if (process_options(argc, argv, &net1, &net2) < 0) {
        return -1;
    }

    if (0 == net1.ip || 0 == net1.mask || 0 == net2.ip || 0 == net2.mask) {
        dbg("no valid net(%u/%u)(%u/%u)", net1.ip, net1.mask, net2.ip, net2.mask);
        return -1;
    }

    conflict = check_conflict(&net1, &net2);

    if (debug_on) {
        dbg("(%u/%u) VS (%u/%u), conflict:%d", net1.ip, net1.mask, net2.ip, net2.mask, conflict);
    }

    return conflict;
}

标签:ip,max,min,IP,mask,C语言,Linux,net2,net1
From: https://www.cnblogs.com/adam-ma/p/17994769

相关文章

  • Linux如何从命令行卡死的进程中退出?
    Linux如何从命令行卡死的进程中退出?不知道大家在使用Linux的时候,会不会遇到一些命令,有可能卡顿,有可能执行时间过长(比如使用find查找某个文件),这个时候我不想继续执行这个命令了,说来惭愧,我之前一直使用Ctrl+Z去终止这个命令,今天才知道,这样有很大的问题!信号简介一个进程在运行的......
  • linux 学习总结
      ├──usr(UnixSystemResources)等同于C:/Windows├──src系统级的源码目录├──bin用于存放用户可执行的二进制文件├──lib存放共享库文件和一些系统级别的函数库等同于C:/Windows/System32├──local用于......
  • Fortify Static Code Analyzer 23.2 for macOS, Linux & Windows - 静态应用安全测试
    FortifyStaticCodeAnalyzer23.2formacOS,Linux&Windows-静态应用安全测试FortifySCA-代码漏洞扫描工具|静态代码测试|代码安全分析请访问原文链接:https://sysin.org/blog/fortify-static-code-analyzer/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.o......
  • 关于ufw 报错ip6tables v1.6.1: can't initialize ip6tables table `filter': Table d
    背景在ubuntuarm版本上安装ufw,设置规则时报错发现报错ip6tablesv1.6.1:can'tinitializeip6tablestable`filter':Tabledoesnotexist(doyouneedtoinsmod?)Perhapsip6tablesoryourkernelneedstobeupgraded.解决办法一.升级ip6tables二.禁用i......
  • C语言设计模式精要
    在C语言中,设计模式是一种常见的方法,它可以帮助我们更好地设计和实现软件系统。设计模式是一种面向对象的设计模式,它可以帮助我们更好地组织和管理代码,提高代码的可读性和可维护性。在C语言中,设计模式主要包括以下几种:单例模式、工厂模式、观察者模式、策略模式、装饰模式等。单......
  • 通过LINUX驱动控制FPGA端PWM外设(LED) 通过应用程序命令传参随意修改寄存器的值(PWM波频
    用法:先下发下面的命令让kernel信息打印到串口:echo7417>/proc/sys/kernel/printk然后增加程序可执行性:chmod777pwmdriver_app  先执行./pwmdriver_app/dev/pwm400000200然后执行./pwm_driver_app/dev/pwm400000200,可以发现LED[1]......
  • AlipayGlobal集成备忘录
    一、获取clientId,publicKey,privateKey登录开发者中心https://global.alipay.com/developer如果当前账号尚未配置publicKey,则需要你下载阿里官方提供的工具去生成一个最终你要使用的publicKey和privateKey分别来自以下两个地方另外开发者中心提供如图所示工具,进行一系......
  • Linux grep命令有何作用?如何使用?
    进行Linux系统维护的时候,想要在文本中快速搜索到你需要的东西,grep命令是非常不错的选择,它主要用于查找文件里符合条件的字符串,从而节省时间、提高工作效率。那么Linux系统中grep命令如何使用?我们一起来看看详细的内容介绍。Linuxgrep命令用于查找文件里符合条件的字符串......
  • [Typescript] Native ES module support
    Node.js13.2.0introducedsupportfornativeESmodules.Thismeansyoucannativelyruncodecontainingthinglike import{Foo}from'bar',usetop-level await andmore!Howtounambiguouslyindicatewhichtypeofmoduleyou’reauthoringFil......
  • 4_物联网IwIP物联网网络开发
    相关技能:1以太网基础硬件设计及外设 TCP/IP协议2IwIP协议栈,RawAPI编程模型,TCP回响服务器的实现3Socket基础,socket接口函数的分析及应用4  FreeRTOS&IwIP的配置,及C/S架构的设计及编程5UDP模型6并发服务器7DNS域名解析,心跳......