【问题标题】:Protocol number for socket creation for UDP protocol为 UDP 协议创建套接字的协议号
【发布时间】:2021-03-05 16:19:47
【问题描述】:

我正在为 C 中的客户端创建套接字。我想使用 UDP 协议,但我似乎无法在手册页中找到它。

int socket(int domain, int type, int protocol);

【问题讨论】:

  • man socket: PF_INET, PF_UNIX.
  • @tadman 他们只给出域协议号而不是 UDP 协议号我只是不知道应该为套接字函数的最后一个参数输入哪个数字
  • @tadman 你能告诉我你是怎么在你发给我的手册页上找到这个的,因为我刚刚迷失在 c 中
  • 对于 IP 上的 UDP:socket(AF_INET, SOCK_DGRAM, 0)。如果你在 C 中学习这个,我发现 this book 非常宝贵。
  • @tadman 我会确保阅读它,非常感谢:)

标签: c sockets


【解决方案1】:

man 2 socket 手册页仅描述了socket() 系统调用的一般用法。它没有详细介绍每种可能的协议。为此,7 部分下有几个不同的手册页。

对于IP协议,您可以查看man 7 ip,其中声明:

An IP socket is created using socket(2):

    socket(AF_INET, socket_type, protocol);

Valid socket types include SOCK_STREAM to open a stream socket,
SOCK_DGRAM to open a datagram socket, and SOCK_RAW to open a
raw(7) socket to access the IP protocol directly.

protocol is the IP protocol in the IP header to be received or
sent.  Valid values for protocol include:

   - 0 and IPPROTO_TCP for tcp(7) stream sockets;
   - 0 and IPPROTO_UDP for udp(7) datagram sockets;
   - IPPROTO_SCTP for sctp(7) stream sockets; and
   - IPPROTO_UDPLITE for udplite(7) datagram sockets.

所以对于你想要的 UDP 套接字:

int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

或等效:

int fd = socket(AF_INET, SOCK_DGRAM, 0);

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 2013-07-27
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多