UB_Roy
UB_Roy

Reputation: 691

UDP packet to a Specific IP in LAN

I have a embedded device in my LAN and a c++ application in Linux in a computer. I have made a UDP broadcast on my subnet broadcast address from C++ and my device returned a message with signature. Both of them have each others IP address now. I need to send a UDP packet from my C++ specifically to my device IP. The initial call to my device was done over UDP, but it was using the broadcast option in socket options. Some of my experiments with packet generation tools gave me a impression that UDP uses MAC ID to find destination. So what should be the method in C++, if I want to send a UDP packet to my specific IP in my LAN? Thanks

Upvotes: 0

Views: 1820

Answers (3)

Sam Skuce
Sam Skuce

Reputation: 1694

Based on your response to stefaanv, it sounds like your question is really "how do I get the IP address from thread A to thread B?", where thread A receives the response to the broadcast message, and thread B does the device-specific communication.

One way you could do this is by creating thread B from thread A, and passing in the IP address as an argument to thread B's function. This way thread B will know from the beginning what IP address to talk to.

If thread B has to be up and running before thread A, you can share the IP address using a global variable, and use, e.g. a semaphore so that thread A can tell thread B when it has set the IP address. Just be sure that thread A is the only thread that writes that global variable, or else you will have to set up another layer of synchronization, e.g. using a mutex, to make sure that writing to the IP address is only done by one thread at a time.

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

If you send out a broadcast and you expect answers via UDP, you should receive them with the recvfrom call. This fills in the address of the sender. The corresponding call to send UDP with the received address information is sendto.

Upvotes: 1

Joe
Joe

Reputation: 7798

You didn't specify O/S, but...

You can make a UDP socket use connect if you want. This then means that further sends to that socket will go to the IP you "connected" to, all this despite UDP being connectionless.

Upvotes: 0

Related Questions