Nyaruko
Nyaruko

Reputation: 4479

How to bind to the correct address and port for UDP communication?

I have build a local area network, the routher is at 192.168.1.1, I have hardware at 192.168.1.10 which is sending UDP packets to 192.168.1.105:14455.

My PC is also in this local area network. Its IP address is randomly assigned by the router. I would like to listen to the packets sent from my hardware at 192.168.1.10.

Currently, I set my PC's address to 192.168.1.105 and bind to 0.0.0.0:14455.

However, if I don't bind to 0.0.0.0 to listen to all address, then which address (x.x.x.x:14455)shall I bind to to listen to my hardware?

Moreover, if I ask the hardware to boardcast over the network. How should I bind my PC (to which x.x.x.x:14455?)?

Upvotes: 1

Views: 2038

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596256

My PC is also in this local area network. Its IP address is randomly assigned by the router. ... Currently, I set my PC's address to 192.168.1.105

That is a contradiction. Either the PC's IP is assigned dynamically by the router, or it is assigned statically on the PC's network adapter. Unless you configure your router to always assign the same IP to your PC, based on the mac address of the PC's network adapter.

However, if I don't bind to 0.0.0.0 to listen to all address, then which address (x.x.x.x:14455)shall I bind to to listen to my hardware?

You would have to bind to whichever IP address is currently assigned to the network adapter that is connected to the network where the packets will be coming from. So, if 192.168.1.105 is assigned to your PC, then you would bind to 192.168.1.105:14455.

Moreover, if I ask the hardware to boardcast over the network. How should I bind my PC (to which x.x.x.x:14455?)?

The same rules applies. You can either bind to 0.0.0.0 to listen on all local IPs, or you can bind to the specific IP that is connected to the network where the broadcasts will be coming from.

Upvotes: 1

SergeyA
SergeyA

Reputation: 62573

For unicasts, you should either bind to INADDR_ANY, or to specific IP address used by the sender (only in case when you have more than IP on the PC). For the broadcast, you should always bind to INADDR_BROADCAST, otherwise you might not see broadcast packets depending on implementation.

Upvotes: 1

Related Questions