Binding to a specific IP address and port to receive UDP data

前端 未结 3 398
说谎
说谎 2021-02-05 23:20

I am trying to receive UDP data that is broadcast to network address 192.168.103.255 port 3000 by PlayCap (http://www.signal11.us/oss/playcap/). I\'m having problems binding to

相关标签:
3条回答
  • 2021-02-06 00:01

    You don't bind to the broadcast address to receive broadcast packets. Just bind to the port and the address INADDR_ANY (sorry, not sure how to express that in Java) and you will get packets to that port on the broadcast address.

    0 讨论(0)
  • 2021-02-06 00:08

    It appears that the Datagram constructor takes the port number to bind to. Hope that helped...

    0 讨论(0)
  • 2021-02-06 00:09

    Try this for your Java code instead:

    public static void main(String[] args) {
        try {
            DatagramSocket s = new DatagramSocket(null);
            InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000);
            s.bind(address);
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    Calling the no-arg constructor for a datagram socket will cause it to bind to a random, available port. Once bound, further attempts to (re)bind will throw a socket exception (with the error you were seeing). To 'defer' binding, you instead create the datagram socket in an unbound state (by passing a null in the constructor), then calling bind later on.

    0 讨论(0)
提交回复
热议问题