笔记-TCP/IP IPv4/IPv6地址比较

IP地址转换函数

在比较IP地址之前需要将其转换为网络字节序的二进制整数,常用的IP地址转换函数是 inet_pton(),其支持IPv4和IPv6.

windows下:
#include <WS2tcpip.h>

linux下:
#include <arpa/inet.h>

int inet_pton(int af, const char *src, void *dst);

转换实例

#include <arpa/inet.h>

int main()
{
	// IPv4
	char *str = "192.168.1.1";
	struct in_addr ipv4; // 保存IPv4地址的结构体
	inet_pton(AF_INET, str, &ipv4); // AF_INET表示IPv4地址协议簇
	
	// IPv6
	char *str6 = "2000::1";
	struct in6_addr ipv6; // 保存IPv6地址的结构体
	inet_pton(AF_INET6, str6, &ipv6); // AF_INET6表示IPv6地址协议簇

	return 0;
}

IP地址比较

原理

大端模式 - 数据的高字节保存在内存的低地址中
小端模式 - 数据的高字节保存在内存的高地址中

以IPv4地址"192.168.2.1" 为例:
下面的例子,第一字节为最低地址,第四字节为最高地址

模式第一字节第二字节第三字节第四字节
大端19216821
小端12168192

所以将需要比较的地址转换为网络字节序(大端模式)后,使用函数 memcmp() 就可以按字节比较两个地址大小。

int memcmp(const void *buf1, const void *buf2, unsigned int count);

比较大小

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

// 简单判断是否为IPv6
bool isipv6(const char* ipstr)
{
    assert(ipstr);
    return !!strchr(ipstr, ':');
}

// IP地址比较,要求两个IP地址同一类型,格式符合标准
int ipcmp(const char* ipstr1, const char *ipstr2)
{
    assert(ipstr1 && ipstr2);
    assert(isipv6(ipstr1) == isipv6(ipstr2)); // 断言 两个IP地址同一类型

    char buf1[sizeof(struct in6_addr)] = {0};
    char buf2[sizeof(struct in6_addr)] = {0};
    int domain = isipv6(ipstr1) ? AF_INET6 : AF_INET;
    int length = domain==AF_INET ? sizeof(struct in_addr) : sizeof(struct in6_addr);
    int s1 = inet_pton(domain, ipstr1, buf1);
    int s2 = inet_pton(domain, ipstr2, buf2);

    assert(s1>0 && s2>0);  // 断言 两个IP格式符合标准

    return memcmp(buf1, buf2, length);
}

int main(int argc, char **argv)
{
    if(argc != 3){
        fprintf(stderr, "usage: %s string string\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int result = ipcmp(argv[1], argv[2]);
    if (result > 0)
        printf("%s is greater than %s\n", argv[1], argv[2]);
    else if (result < 0)
        printf("%s is less than %s\n", argv[1], argv[2]);
    else
        printf("%s is equal to %s\n", argv[1], argv[2]);
    exit(EXIT_SUCCESS);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值