Reputation: 1375
using iphone SDK 3.1.2
If connected via 3G on the iphone to internet, how do i find out what ip address is being used for this interface.
Thanks
Upvotes: 0
Views: 5335
Reputation: 181460
Here is a code piece that might help:
// Matt Brown's get WiFi IP addy solution
// Author gave permission to use in Cookbook under cookbook license
// http://mattbsoftware.blogspot.com/2009/04/how-to-get-ip-address-of-iphone-os-v221.html
+ (NSString *) localAddressForInterface:(NSString *)interface {
BOOL success;
struct ifaddrs * addrs;
const struct ifaddrs * cursor;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
// the second test keeps from picking up the loopback address
if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
{
NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
if ([name isEqualToString:interface]) // Wi-Fi adapter
return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return nil;
}
+ (NSString *) localWiFiIPAddress
{
return [UIDevice localAddressForInterface:@"en0"];
}
+ (NSString *) localCellularIPAddress
{
return [UIDevice localAddressForInterface:@"pdp_ip0"];
}
I am not trying to get credit for this piece of code myself. Here's the original URL.
Key function call is getifaddrs.
Hope it helps.
Upvotes: 2