Michael
Michael

Reputation: 115

UDP socket, select one of multiple clients


here's what I'm trying to do:
I have 4 clocks and one PC on the network. I (PC) want to get the time from any of the clocks.

The idea:
Every clock uses UDP Broadcast (broadcast because I don't know the PC's IP). The PC gets a first dataset(time) and from then on only looks at datasets from this clock. (To not get confused by slight timedifferences between the clocks)

Clocks=Clients:
- socket
- bind to port 1234
- sendto(broadcast,'1234')

PC=Server
- socket
- bind to port 1234
- recvfrom(data,client_addr) //extract client_addr from first received data
- connect(client_addr) //to only receive data from this client
- recvfrom()

1: Is this the correct way to do this? Or is there a better option?

2: What can I do, if I want more than one application on the PC to get the time-data? Can I just copy the code and use it? My impression was, that port 1234 is now blocked from the first application that gets the bind. (I guess SO_REUSEADDR won't work because only ONE application then gets the data AND I don't know which one it is going to be)

Regards

Upvotes: 2

Views: 1044

Answers (1)

user207421
user207421

Reputation: 311054

1: Is this the correct way to do this?

Yes.

Or is there a better option?

Can't think of one off-hand.

2: What can I do, if I want more than one application on the PC to get the time-data?

Use SO_REUSEADDR.

Can I just copy the code and use it?

Yes.

My impression was, that port 1234 is now blocked from the first application that gets the bind.

No.

(I guess SO_REUSEADDR won't work because only ONE application then gets the data AND I don't know which one it is going to be)

Wrong guess. Why guess about it at all? Why not try it? Much more reliable than guessing, and quicker than asking questions here too.

Upvotes: 2

Related Questions