首页 > 代码库 > sendto函数的坑

sendto函数的坑

  测试unix数据报套接字时,一个程序收,一个程序发,分别绑定自己的socket。结果在收的部分,返回的发送方的地址总是空的,但是返回的地址长度又是对的。

while ( 1 )
{
      bzero(&clientaddr, sizeof(struct sockaddr_un));
      slen = 0;
      rn = recvfrom(fd,buf, sizeof(buf), 0 ,(struct sockaddr *)&clientaddr, slen);
      if ( rn == -1)
      {
                perror("recvfrom");
      } 
      buf[n] = 0;   
}

      仔细对比unp的代码,发现   slen = 0  这行改成   slen = sizeof(strcut sockaddr_un) 结果就对了,细看man

  ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);
=====================================================================================================================
    If src_addr is not NULL, and the underlying protocol provides the source address, this source address is filled in. When src_addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL. The argument addrlen is a value-result argument, which the caller should initialize before the call to the size of the buffer associated with src_addr, and modified on return to indicate the actual size of the source address. The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.

  红色部分指出,最后一个参数addrlen是一个"值-结果"的参数,赋给它的初始值用来指定拷贝到倒数第二个参数 src_addr 里面的字节数,返回实际值是实际的源地址结构的大小。当传入的参数小于输出的值,说明返回的源地址被截断了。

上面的例子中,传入的值为0,而输出的值大于0,明显这里有问题,未拷贝任何数据到返回的源地址clientaddr。

sendto函数的坑