0

我正在编写一个 ping 克隆来练习套接字编程。我能够发送 ICMP 数据包,但目标地址是 0.0.0.0,无论我传递什么sendto。这是最相关的代码片段:

struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
if (0 == inet_aton(argv[1], &dest.sin_addr)) {
  puts("could not parse address\n");
  exit(EXIT_FAILURE);
}

ssize_t nbytes = sendto(sock, &hdr, ICMP_MINLEN, /*flags=*/0,
    (struct sockaddr*)&dest, sizeof(dest));

完整的程序在 GitHub 上。我正在为 Mac OS X 10.6.8 进行编译,并且正在使用 Wireshark 1.8.4 来验证数据包。

dest.sin_addr.s_addr我已经通过调用验证了 的值printf("%X"),并且inet_aton按预期工作。我什至特意将它设置为0x08080808(谷歌的名称服务器),它仍然不起作用。

我在这里可能做错了什么?

4

1 回答 1

1

There's one (copy-paste) bug in your full program on github:

struct sockaddr_in src;
memset(&dest, 0, sizeof(dest));

After declaring src, you memset dest again. This means that dest's sin_addr member is now 0 so you're requesting a destination address of 0.0.0.0.

As an aside, src's sin_port is left uninitialised so you may sometimes get other errors if you end up requesting a local port that is already in use.

于 2012-12-10T09:21:44.870 回答