1

我正在通过 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”。

问题可能出在哪里?

4

1 回答 1

3
inet_pton(AF_INET, ...);

应该将 astruct in_addr作为第三个参数(参见docs)。

你给它sa_data,从

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

这实际上被视为:

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
};

因此,前 16 位进入端口,IPV4 地址的后 16 位实际上进入sin_addr,其余的似乎是零初始化的。


应该这样做(为了清楚起见,我会放很多演员表)

struct sockaddr *addr = &self->hostAddress; // generic address
struct sockaddr_in *ipv4 = (struct sockaddr_in *)addr; // downcast to ipv4
inet_pton(AF_INET, "173.194.67.93", &ipv4->sin_addr);
于 2012-10-22T15:42:27.433 回答