c - BSD - 使用任何可用的端口?

标签 c sockets port bind 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 连接,它们应该使用不同的端口吗? (不觉得这值得另一个问题)

最佳答案

Seems like that case makes doing that a bad idea

不是这样,见下文。

Is there a way to say "find and use any open port"?

当然,您可以不绑定(bind) 或将NULL 作为端口 传递。但是,客户如何知道连接到哪里?您必须在某处发布此信息。

回到绑定(bind)(2)。如果您指定 0 端口,内核会在调用 bind 时选择一个临时端口。

这是来自 TLPI 的引述:

There are other possibilities than binding a server’s socket to a well-known address. For example, for an Internet domain socket, the server could omit the call to bind() and simply call listen(), which causes the kernel to choose an ephem- eral port for that socket.

Afterward, the server can use getsockname() to retrieve the address of its socket. In this scenario, the server must then publish that address so that clients know how to locate the server’s socket. Such publication could be done by registering the server’s address with a centralized directory service application that clients then contact in order to obtain the address.

回到你的问题:

Also quick question - if I am using both tcp and udp connections in an application, should they use different ports

不一定。他们不会“混淆”。

关于c - BSD - 使用任何可用的端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081812/

相关文章:

sockets - TCP:是否可以绑定(bind)一个套接字然后/两者/从它连接并接受它(客户端和服务器规则)?

c - 使用lua的lightuserdata注册定时器回调

c - 在 fget 之前进行扫描

c - C 中的字符串搜索操作

c - gl.h 包含在 glew 之前,但 GLFW 需要 gl.h

javascript - 使用 socket.io 发送确认,说我的函数未定义

php - 如何打开wss : or ws: port on my website?

linux - UDP 数据包到达 Linux 上的错误套接字

c# - 为什么我需要在套接字上定义端点两次才能开始接收数据?

Hadoop端口50070在使用Windows安装错误