socket的protocal参数

Documentation for socket() on Linux is split between various manpages including ip(7) that specifies that you have to use 0 or IPPROTO_UDP for UDP and 0 or IPPROTO_TCP for TCP. When you use 0, which happens to be the value of IPPROTO_IP, UDP is used for SOCK_DGRAM and TCP is used for SOCK_STREAM.

In my opinion the clean way to create a UDP or a TCP IPv4 socket object is as follows:

int sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int sock_tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

The reason is that it is generally better to be explicit than implicit. In this specific case using 0 or worse IPPROTO_IP for the third argument doesn't gain you anything.

Also imagine using a protocol that can do both streams and datagrams like sctp. By always specifying both socktype and protocol you are safe from any ambiguity.

转载于:https://www.cnblogs.com/liyulong1982/p/6904007.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值