sockaddr_in变量的存储大小未知

时间:2013-04-22 18:53:59

标签: c sockets gcc freebsd

我有很长一段时间以前在某些环境中工作的代码。我很确定它是一台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,但我真的迷路了。

有什么想法吗?

5 个答案:

答案 0 :(得分:6)

我将你的代码剪切并粘贴到一个文件中(仅删除#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>

希望这有帮助

答案 1 :(得分:6)

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

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

  • 如果您正在使用struct sockaddr_in#include <netinet/in.h>
  • 如果您正在使用struct sockaddr_un#include <sys/un.h>
  • 如果您正在使用struct sockaddr_ns#include <netns/ns.h>
  • 如果您正在使用struct sockaddr_ndd#include <sys/ndd_var.h>

有关套接字编程头文件的更多信息,请参见here

答案 2 :(得分:4)

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

#include <arpa/inet.h>

答案 3 :(得分:4)

只需将#include <resolv.h>添加到您的来源,就可以了。

答案 4 :(得分:2)

根据你需要的freebsd developer's handbook

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