【问题标题】:Is there a way to bind a DatagramSocket to any port on a specific nic or if I specify the nic I have to specify the port?有没有办法将 DatagramSocket 绑定到特定网卡上的任何端口,或者如果我指定网卡我必须指定端口?
【发布时间】:2012-09-13 19:56:28
【问题描述】:

这在 Java 中是不可能的吗? DatagramSocket.bind 方法必须采用 NULL 或 IP:PORT。您不能只传递描述 NIC 的 IP,然后自动选择 PORT。除非我遗漏了一些东西,否则这有点没有意义。

【问题讨论】:

标签: java sockets networking udp


【解决方案1】:

使用DatagramSocket的默认构造函数。这将绑定到任何端口。您不必使用 bind 方法。

【讨论】:

  • 我使用的是NIO,所以我没有使用构造函数而是:channel = DatagramChannel.open();
【解决方案2】:

只需指定一个端口号为零,或者按照 Mike Q 的建议省略它。在这两种情况下,系统都会为您分配一个端口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多