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

时间:2016-04-05 18:42:11

标签: c sockets binary ip bitmask

我正在寻找使用套接字在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);

1 个答案:

答案 0 :(得分:2)

导致错误的原因是,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;

到此:

mpApp.FileOpen Name:=file_location_and_name, ReadOnly:=True, openPool:=pjDoNotOpenPool