如何正确填充套接字地址?

时间:2012-10-22 15:35:47

标签: c sockets

我通过iOS中的套接字发送ICMP数据包:

struct sockaddr         hostAddress;

self->hostAddress.sa_family = AF_INET;
inet_pton(AF_INET, "173.194.67.93", &self->hostAddress.sa_data);

然后,我打开套接字并发送数据包:

bytesSent = sendto(
                   CFSocketGetNative(self->_socket),
                   [packet bytes],
                   [packet length],
                   0,
                   &self->hostAddress,
                   sizeof(self->hostAddress)
                   );

当我在WireShark中看到数据包时,它被发送到“67.93.0.0”,而不是“173.194.67.93”。

哪里可能是问题?

1 个答案:

答案 0 :(得分:3)

inet_pton(AF_INET, ...);

应该以{{1​​}}作为第三个参数(参见docs)。

你从

给它struct in_addr
sa_data

真的被视为:

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

因此,前16位进入端口,IPV4地址的后16位实际上进入struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; ,其余的似乎是零初始化。


应该这样做(为了清楚起见,我会加载大量的演员表)

sin_addr