【问题标题】:Storage size of sockaddr_in variable isn't knownsockaddr_in 变量的存储大小未知
【发布时间】:2013-04-15 19:01:51
【问题描述】:

我有一段很久以前在某个环境中工作的代码。我很确定这是一台 FreeBSD 机器,所以我得到了 FreeBSD 8.3,我正在尝试制作这个文件,但它不起作用。

当我尝试编译它时,它会抱怨:

f.c: In function 'tcp'>
f.c:24: error: storage size of 'socket_stru' isn't known
f.c:29: error: 'IPPROTO_TCP' undeclared (first use in this function)
...

我环顾四周,发现这些都在 sys/socket.h 文件中指定。这是我的实际文件:

#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>


#include "f.h"

int tcp4 (in_addr_t ip, int port, int qsize )
{   
    struct sockaddr_in socket_stru; // line 24
    socket_stru.sin_family = AF_INET;
    socket_stru.sin_port = htons(port);
    socket_stru.sin_addr.s_addr = ip;

    int actual_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); // line 29
...

我觉得我的代码不知何故没有“读取” sys/socket.h 文件,所以它不知道 socket_stru 和 IPPROTO_TCP,但我真的迷路了。

有什么想法吗?

【问题讨论】:

    标签: c sockets gcc freebsd


    【解决方案1】:

    其他答案都不适合我。查看sys/socket.h 文件后,我什至没有看到struct sockaddr_in 的定义。

    当使用相应的struct sockaddr_* 类型时,对我有用的是#include 以下文件之一:

    • 如果您使用的是struct sockaddr_in,#include &lt;netinet/in.h&gt;
    • 如果您使用的是struct sockaddr_un,#include &lt;sys/un.h&gt;
    • 如果您使用的是struct sockaddr_ns,#include &lt;netns/ns.h&gt;
    • 如果您使用的是struct sockaddr_ndd,#include &lt;sys/ndd_var.h&gt;

    更多关于套接字编程头文件的信息可以在here找到。

    【讨论】:

      【解决方案2】:

      我将您的代码剪切并粘贴到一个文件中(仅删除 #include f.h 并关闭函数调用。)它在 Linux 上编译得很好。

      我怀疑 BSD 上的头文件可能存在差异。对于套接字编程,我通常包括所有这些头文件。而且我知道我的套接字代码也可以在 BSD 上编译。我怀疑其中一个头文件引入了 sockaddr_in 的定义。我记得当我通过套接字代码移植到 BSD 时,我不得不显式添加其中的一些。

      #include <sys/types.h>
      #include <sys/socket.h>
      #include <netinet/in.h>
      #include <unistd.h>
      #include <arpa/inet.h>
      #include <netdb.h>
      #include <unistd.h>
      #include <signal.h>
      #include <stdio.h>
      #include <string.h>
      #include <fcntl.h>
      #include <errno.h>
      #include <sys/time.h>
      #include <stdlib.h>
      #include <memory.h>
      #include <ifaddrs.h>
      #include <net/if.h>
      #include <stdarg.h>
      /* the next two includes probably aren't relevant for you, but I typically use them all anyway */
      #include <math.h>
      #include <sys/termios.h>
      

      希望对你有帮助

      【讨论】:

      【解决方案3】:

      我遇到了同样的问题,但以下内容为我解决了问题

      #include <arpa/inet.h>
      

      【讨论】:

        【解决方案4】:

        只需将#include &lt;resolv.h&gt; 添加到您的来源即可。

        【讨论】:

          【解决方案5】:

          根据freebsd developer's handbook你需要

          #include <stdio.h>
          #include <string.h>
          #include <sys/types.h>
          #include <sys/socket.h>
          #include <netinet/in.h>
          

          【讨论】:

            猜你喜欢
            • 2022-06-14
            • 1970-01-01
            • 2017-07-24
            • 1970-01-01
            • 1970-01-01
            • 2022-07-08
            • 2019-06-30
            • 1970-01-01
            相关资源
            最近更新 更多