1

私がオンラインで見つけたすべてのチュートリアルと例では、常に 7000 や 495​​0 などのポート番号が指定されています。その場合、それを行うのは悪い考えのようです。「開いているポートを見つけて使用する」と言う方法はありますか? 私のコードは今このようなものです -

//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 接続の両方を使用している場合、別のポートを使用する必要がありますか? (これは別の質問に値するとは思わなかった)

4

1 に答える 1

2

Seems like that case makes doing that a bad idea

Not so, see below.

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

Sure, you could just not bind or pass NULL as port. 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 of 0 the kernel chooses an ephemeral port when bind is called.

Here's a quote from 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.

Back to your questions:

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

Not necessarily. They don't "get mixed up".

于 2011-08-16T16:53:21.880 に答える