端口为零的绑定会将您绑定到空闲端口.这是便携式的吗? [英] A bind with a port of zero will bind you to a free port. Is this portable?

查看:98
本文介绍了端口为零的绑定会将您绑定到空闲端口.这是便携式的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望程序绑定到空闲端口.

I want my program to bind to a free port.

Google告诉我,使用port = 0进行绑定可以做到这一点,但是我还不确定是否可以保证在任何系统(特别是Windows/Linux)上都可以使用此功能.

Google told me that a bind with port=0 will do that, but I haven't found if this is guaranteed to work on any system (Windows/Linux in particular).

有人可以链接这样说的文档吗?

Can someone link a doc that say that?

推荐答案

据我所知,它是通用的,但我在标准中找不到任何文字.可能更可移植的替代方法是将getaddrinfo与空服务名指针和AI_PASSIVE标志一起使用.这可以保证为您提供bind您可以使用的sockaddr.这也是让管理员选择哪个本地IP(v4或v6)的正确方法 要绑定的地址.

It's universal as far as I know, but I can't find any text in the standards that says it is. An alternative that might be more portable is using getaddrinfo with null service name pointers and the AI_PASSIVE flag. This is guaranteed to give you an sockaddr you can bind to. It's also the correct way to let the administrator choose which local ip (v4 or v6) address to bind to.

这篇关于端口为零的绑定会将您绑定到空闲端口.这是便携式的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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