How can I know the IP address of a remote host by using UDP broadcast message?
I am developing an embedded system and very new to this TCP\IP. My problem is that once I installed my board in a local network and this board will acquire its IP address dynamically, it has to communicate with a client application running on one of the PC(other than DH开发者_运维技巧CP server) in the network. To communicate with this new board the client application is required to know the IP address of the board. What is the way to know the IP address of the board? Will UDP broadcast work for this purpose? If yes please, explain in detail as I am unable to understand it. Please provide me some sample code in C if possible.
The basic idea is:
- Embedded system software opens a UDP socket, binds it to a well-known port and sets the
SO_BROADCAST
socket option withsetsockopt()
. It then callsrecvfrom()
to wait for packets in a loop. - Define a packet format that allows a packet type to be specified. Define a "discovery" packet type.
- If the embedded system recieves a "discovery" packet, it responds to the sender with a packet that might contain its name/serial number/uptime/status.
- Client software opens a UDP socket, sets the
SO_BROADCAST
socket option and sends a "discovery" type packet to the well-known port and the local broadcast address. - Client software waits for response(s) from each embedded system with
recvfrom()
, recording the address of each. - Client picks an embedded device and starts communicating directly with it.
I don't know how limited your resources are but the best solution would be to include a mDNS solution like http://avahi.org/ on your board. There have specific configurations that target embedded platforms.
The beneficial part of this is that you will will be hooking into a standard mechanism for service discovery which buys you a lot if you can play well with others. Avahi is LGPL but there are other versions that are some version of BSD and ASPL(?)
精彩评论