BSD - 使用任何可用的端口?
我在网上找到的所有教程和示例总是指定一个端口号,如 7000 或 4950 等。如果这些端口在一台计算机上打开,但在另一台计算机上打开怎么办?看起来这个案子使得这样做是一个坏主意。有没有办法说“查找并使用任何开放端口”?我的代码现在是这样的 -
//get server info, put into servinfo
if ((status = getaddrinfo("192.168.2.2", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
端口为 4950。这是用于 tcp 套接字的,但我假设它与 udp 的一般策略相同?
还有一个简单的问题 - 如果我在应用程序中同时使用 tcp 和 udp 连接,它们应该使用不同的端口吗? (觉得这不值得再问一个问题)
All of the tutorials and examples I find online always specify a port number like 7000 or 4950 etc. What if those ports are open on one computer, but another? Seems like that case makes doing that a bad idea. Is there a way to say "find and use any open port"? My code now is like this -
//get server info, put into servinfo
if ((status = getaddrinfo("192.168.2.2", port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
with port being 4950. This is for a tcp socket, but I'm assuming it will be the same general strategy for udp?
Also quick question - if I am using both tcp and udp connections in an application, should they use different ports? (didn't feel like this deserved another question)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并非如此,请参见下文。
当然,您可以不
绑定
或将NULL
作为端口
传递。但是,客户端如何知道连接到哪里?您必须在某处发布此信息。返回
bind(2)
。如果您指定端口0
,则内核会在调用bind 时选择一个临时端口。引用 TLPI 的一段话:
回到你的问题:
不一定。他们不会“混淆”。
Not so, see below.
Sure, you could just not
bind
or passNULL
asport
. But then, how would the clients know where to connect to ? You would have to publish this information somewhere.Back to
bind(2)
. If you specify a port of0
the kernel chooses an ephemeral port when bind is called.Here's a quote from TLPI:
Back to your questions:
Not necessarily. They don't "get mixed up".