glusterfs

Форк
0
/
ip-in-cidr.c 
69 строк · 1.5 Кб
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <sys/types.h>
5
#include <sys/socket.h>
6
#include <netinet/in.h>
7
#include <errno.h>
8
#include <netdb.h>
9

10
int
11
gf_is_ip_in_net(const char *network, const char *ip_str)
12
{
13
    /* A buffer big enough for any socket address. */
14
    uint8_t net_buff[sizeof(struct sockaddr_storage) + 1];
15
    uint8_t ip_buff[sizeof(struct sockaddr_storage) + 1];
16
    int32_t size;
17
    uint8_t mask;
18
    int ret = 0;
19
    int family = AF_INET;
20

21
    if (strchr(network, ':'))
22
        family = AF_INET6;
23
    else if (strchr(network, '.'))
24
        family = AF_INET;
25
    else {
26
        goto out;
27
    }
28

29
    size = inet_net_pton(family, network, net_buff, sizeof(net_buff));
30
    if (size < 0) {
31
        fprintf(stderr, "inet_net_pton: %s\n", strerror(errno));
32
        goto out;
33
    }
34

35
    ret = inet_pton(family, ip_str, &ip_buff);
36
    if (ret < 0) {
37
        fprintf(stderr, "inet_pton: %s\n", strerror(errno));
38
        goto out;
39
    }
40

41
    mask = (0xff00 >> (size & 7)) & 0xff;
42
    size /= 8;
43
    net_buff[size] &= mask;
44
    ip_buff[size] &= mask;
45

46
    return memcmp(net_buff, ip_buff, size + 1) == 0;
47
out:
48
    return ret;
49
}
50

51
int
52
main(int argc, char *argv[])
53
{
54
    if (argc < 2) {
55
        fprintf(stderr, "Syntax: ip_in_cidr <subnet_address> <ip_address>");
56
        return 1;
57
    }
58
    char *subnet_str = argv[1];
59
    char *ip_addr = argv[2];
60
    int result = 0;
61

62
    result = gf_is_ip_in_net(subnet_str, ip_addr);
63
    if (result) {
64
        fprintf(stdout, "YES\n");
65
    } else {
66
        fprintf(stdout, "NO\n");
67
    }
68
    return 0;
69
}
70

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.