zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    非递归实现二叉树先序、中序和后序遍历
    领益科技:Windows Server 2012 R2 强制卸载域控制器
    Zabbix调优不完全指南(https://www.jianshu.com/p/2d911d55448f)
    Linux下基础查看命令
    Linux下的快捷键
    给Linux系统新增加一块硬盘
    领益智造:Windows中的备份和还原
    领益智造:AD中修改OU下面用户的属性
    领益科技:AD中批量创建域用户(创建Mac地址账号)
    Linux常见企业面试题
  • 原文地址:https://www.cnblogs.com/thammer/p/6517987.html
Copyright © 2011-2022 走看看