Reputation: 856
I am developing a program in C# which should run on a raspberry pi.
It uses multicast to detect other devices in the network, and in order to do that, I need to get all IPs of the raspi. The code to do that was found in another SO question and works well, with one exception: The call to Dns.GetHostAddresses()
hangs forever, but only some times. Other times it works just like it should.
The code is part of a loop which continuously sends multicast packages with an interval of 2 seconds until it receives an answer from another device. The really strange thing is that this happens ONLY on the first iteration of the loop. If the call returns in the first iteration returns, all following iterations will also succeed.
There are two instances of this class running in separate threads at the same time, if that is relevant.
The exact line which hangs is
IPAddress[] ips = Dns.GetHostAddresses (Dns.GetHostName ());
foreach (IPAddress localIp in ips) {...}
The Dns.GetHostName ()
part correctly returns the string "raspberrypi"
each time, regardless of whether it hangs or not.
Any ideas why this hangs? Is the error most likely to be in the OS (raspbian), in Mono, or in my code?
If more code is needed, please tell me. It is mostly the same as in the answer linked above. The only thing happening before this call is starting a thread which will listen for responses to the multicast packages
Edit: I tried another approach, found in another SO question. Same problem. It hangs forever
The new code:
IPHostEntry iphostentry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress localIp in iphostentry.AddressList) {...}
Upvotes: 1
Views: 669
Reputation: 856
For my particular problem, which is "how do I send UPD packages on all IPs on all interfaces on the local computer", following Damien_The_Unbeliever's suggestion of using NetworkInterface worked. The following code appears to do what I want:
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces ()) {
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
IPAddress localIp = ip.Address;
...
}
}
This does, however, not answer why Dns.GetHostAddresses()
hangs indefinetly
Upvotes: 2
Reputation: 484
I just ran your code in Linqpad (windows) and it works fine. Your problem might be from an external cause. So i'd look at the OS and/or framework you're using.
Upvotes: 0