1

当我recvfrom() 时,收到的消息是正确的,但源地址完全是一团糟,为什么会这样?

char traid_messageR[MAXDATASIZE];
socklen_t addlen;
struct sockaddr_in source_addr;
if((numbytes=recvfrom(udp_sockfd, traid_messageR, 256, 0, (struct sockaddr*)&source_addr, &addlen)) == -1)
{
    perror("recvfrom");
    exit(1);
}

结果是这样的:

(gdb) print source_addr
$1 = {sin_family = 61428, sin_port = 42, sin_addr = {s_addr = 49809}, 
  sin_zero = "\234\352\377\277\310\352\377\277"}

49809 看起来像一个端口号,但它是此接收器的端口号...有人知道这是为什么吗?非常感谢哦,另一件事,我在 select() 循环中使用了它,IF_ISSET(und_socked ,%fds),然后执行上面的代码,有影响吗?

4

2 回答 2

3

you didn't assign value to addlen

addlen = sizeof(source_addr)

UPDATE: refer to http://pubs.opengroup.org/onlinepubs/7908799/xns/recvfrom.html The manual says

address_len Specifies the length of the sockaddr structure pointed to by the address argument. ..... If the address argument is not a null pointer and the protocol provides the source address of messages, the source address of the received message is stored in the sockaddr structure pointed to by the address argument, and the length of this address is stored in the object pointed to by the address_len argument.

于 2013-10-24T05:08:28.920 回答
1

我发现它在这里解释得更好:

在这种情况下,addrlen 是一个值结果参数。在调用之前,应该将其初始化为与 src_addr 关联的缓冲区的大小。返回时,addrlen 被更新以包含源地址的实际大小。

http://man7.org/linux/man-pages/man2/recv.2.html

于 2014-05-09T14:43:57.977 回答