是否总是需要绑定套接字? [英] Is it always required to bind a socket?

查看:122
本文介绍了是否总是需要绑定套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我的问题可能看起来很基本,但是我是网络编程方面的新手. 我想知道:

Well, my question may look like a basic stuff, but i am new to network programming side. I wish to know:

1)是否总是需要绑定套接字才能接收来自该套接字的消息?我看到了一个嗅探器代码(原始套接字),其中一个代码直接调用recvfrom,而另一个代码中它调用bind然后是接收.

1) Is it always required to bind a socket in order to receive message from that? I saw a sniffer code (raw socket) one in which directly it is invoking recvfrom and another piece of code in which it is invoking bind and then a receive.

2)AF_ *和PF_ *系列有什么区别?后者与POSIX有关吗? 推荐哪一个?

2) What is the difference between the AF_* and PF_* family? Is the later related to POSIX? Which is the one recommended ?

推荐答案

不,您不需要bind().

No, you don't need to bind().

如果您打算使用connect或使用sendto()将数据包发送到目标的TCP或UDP套接字,则当您尝试执行以下操作时,内核会自动将套接字绑定到合适的端口号连接或发送.通常,这是首选方式.绑定客户端套接字被认为是有害的.

If you're using a TCP or UDP socket where you are planning to either connect() or send a packet to a destination with sendto(), the kernel will automatically bind the socket to a suitable port number when you try to connect or send. This is generally the preferred way. bind()ing client sockets is considered harmful.

AF_UNIX套接字也是如此-客户端不需要绑定,并且通常不应这样做.

The same is also true of AF_UNIX sockets - the client side does not need to bind, and should not do so normally.

这篇关于是否总是需要绑定套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆