Ran into a need to dynamically determine the current UDP broadcast address for the WiFi interface on the ole’ iPhone. Since NSHost appears to be a private API even w/the 3.0 software, it seems one must go lower. I wrapped it up in a neat little bundle that seems fairly usable if not verbose and full of magic (but understandable) numbers.

A few things of note. en0 is the WiFi interface. There are others. Instrument the following code w/some debug to get them all out. The ip/netmask methods return nil when the WiFi interface is not active. I would also be shocked if there were no corner cases I am ignoring…

6 Comments

I have not tested your code yet, but it appears to solve at least *part* of a problem that I’ve got.

The other part is, I need to actually send a UDP broadcast message to the WiFi broadcast address, from my iPhone, and listen for a response. I’ve found a bunch of examples, mostly linux-based, but all of them fail on the iPhone. Here’s my code – what fails is listed below it:

The above code always fails at the sendto() call, and errno is set to 49 (EADDRNOTAVAIL). perror() gives me sendto: Can't assign requested address. I happen to know that the WiFi network broadcast address is 10.255.255.255 – that's why that value is hard coded. But I still can't send to it. Arrrgh!

Incidentally, your code (if it works) would solve the other part of my problem, which is finding the broadcast address in the first place.

Thanks, Nick. It appears to be working now. After much experimentation, the solution to my original problem was to bind the UDP socket to the WiFi interface address, not to the broadcast address for that interface – and your code for finding the WiFI interface address solved it. Actually, I managed to do it with just the getifaddrs() call you had inside ipAddressForInterface[].

I’m not sure if I agree with your assessment that it’s always best to work on objective-C. This particular bit of code that I’m working on has to be portable to OS X, Linux, and WIn32, as well as iPhone OS, so keeping it all in C is really the only option. And if it works OK on all 4 platforms … why not?