Original: Http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone
For my app, Quickpic, I needed to show the user IP address of the their iPhone so they could type in the URL to the browse R. The IPhone SDK provided no simple way "to get" IP address for the WiFi connection. There are some undocumented methods that work ([Nshost addresses]) but I didn ' t want to risk them Re and my app breaking. So I wrote some C code (cobbled together to various sources) that'll loop through the network interfaces and retrieve The IP address.
Here's a objective-c method to retrieve the IP address of the WiFi connection as a nsstring.
-(NSString *) getipaddress {nsstring *address = @ "error";
struct Ifaddrs *interfaces = NULL;
struct Ifaddrs *temp_addr = NULL;
int success = 0;
Retrieve the current Interfaces-returns 0 on success success = Getifaddrs (&interfaces);
if (success = = 0) {//Loop through linked list of interfaces temp_addr = interfaces; while (temp_addr!= NULL) {if (temp_addr->ifa_addr->sa_family = = af_inet) {//Check if interface is En0 which is the WiFi connection on the IPhone if ([[NSString Stringwithutf8string:temp_addr->ifa_name] IsEqual tostring:@ "En0"]) {//Get nsstring from C String address = [NSString Stringwithutf8string:inet_ntoa (
(struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)];
}} temp_addr = temp_addr->ifa_next;
}//Free memory Freeifaddrs (interfaces);
return address; }
Update (7/10/09): If this isn ' t working for your may need to include the following C headers in the top of your class I Mplementation as
#include <ifaddrs.h>
#include <arpa/inet.h>
Note:this code would work with the Simulator as a-though the interface May is en0. The IPhone Simulator seems to just use the underlying active MAC OS X network interface. On my MacBook pro-using WiFi, this is EN1, but your mileage may vary.
This would also work in Mac OS X since the IPhone OS and Mac OS X both use a lot the same UNIX underpinnings.