套接字:如何使用 inet_pton() 屏蔽二进制形式的 ip 地址

Sockets: How to mask binary form of ip address using inet_pton()

我正在寻找使用套接字对 ip 地址执行掩码操作的正确方法。我尝试使用 inet_pton 将 ip 地址转换为二进制,然后执行二进制和 (&),但编译器抱怨我无法将 sin_addr 转换为 unsigned int。有人可以指导我执行此操作的正确方法吗?

struct sockaddr_in sa;
struct sockaddr_in maska;
char str[INET_ADDRSTRLEN];
// store IP address and mask in sockaddr structs:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));
inet_pton(AF_INET, "255.255.255.0", &(maska.sin_addr));

// Try to perform mask
sa.sin_addr = (unsigned long)sa.sin_addr & (unsigned long)maska.sin_addr;

// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str);

错误的产生是因为您将 sa.sin_addr 分配为 unsigned long 而实际上它是 struct in_addr.

struct sockaddr_in {
    short            sin_family;
    unsigned short   sin_port;
    struct in_addr   sin_addr;
    char             sin_zero[8];
};

您应该使用包含地址的成员。

struct in_addr {
    unsigned long s_addr;
};

更改此行:

sa.sin_addr = (unsigned long)sa.sin_addr & (unsigned long)maska.sin_addr;

对此:

sa.sin_addr.s_addr = sa.sin_addr.s_addr & maska.sin_addr.s_addr;