How to get the external ip in Objective-C - iphone

I looked for some code that will help me to get the ip that the iPhone connect with.
I find this one:
- (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] isEqualToString:#"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;
}
but the problem is that he get me this ip
10.0.0.1
How to get the external ip?

The easiest way to get your internet ip address from code is to use NSURLConnection.
For the URL you can use:
http://www.whatismyip.com/m/mobile.asp
or
http://checkip.dyndns.com/
Just parse the return data and you have your external ip address.

Have a look at the example in my second Answer here.
In a nutshell it uses *http://www.dyndns.org/cgi-bin/check_ip.cg*i to get the extenal I.P

Check Apple's PortMapper, does exactly what you want.
As of iOS7 this is irrelevant.

Late to the party, but https://api4.ipify.org or http://api4.ipify.org returns nothing else but the external IPv4 address of your connection. Code:
NSURL *ipifyUrl = [NSURL URLWithString:#"https://api4.ipify.org/"];
NSString *externalAddr = [NSString stringWithContentsOfURL:ipifyUrl encoding:NSUTF8StringEncoding error:nil];
https://api6.ipify.org returns the external IPv6 address and https://api64.ipify.org either the IPv4 or the IPv6 address. Simple documentation can be found at https://www.ipify.org

Related

IP Address Lookup using Hostname when Bonjour is off in iOS

I just like to ask if it is possible to identify the IP Address of a device (e.g. a printer) using its Hostname even if its Bonjour setting is turned off? Also can you give me an example on how to do it? I am developing an app in iOS that should handle this scenario.
I have looked at the following:
getaddrinfo
CFHostStartInfoResolution
but they work only if the device's bonjour is turned ON.
Assuming the hostname (let's say nameOfTheDevice) is registered with the zone's authoritative DNS server, you can use CFHost to look up an address or hostname. For example:
NSString* hostname = #"nameOfTheDevice";
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
Boolean lookup = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL);
NSArray* addresses = (NSArray*)CFHostGetAddressing(hostRef, &lookup);
[addresses enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *strDNS = [NSString stringWithUTF8String:inet_ntoa(*((struct in_addr *)obj))];
NSLog(#"Resolved %d->%#", idx, strDNS);
}];
(Remember to put error checks in your production code). Bear in mind that if the DNS server isn't aware of that hostname, there's nothing you can do. It's not safe to assume that you'll be able to perform a successful lookup, especially on a home network where built-in DHCP/DNS servers have widely varying capabilities.
From previous answer get callback func and pass obj as a parameter into this function
void printAddr(CFDataRef address)
{
NSString *addressString;
struct sockaddr *addressGeneric;
NSData *myData = (__bridge NSData*)address;
addressGeneric = (struct sockaddr*)[myData bytes];
switch(addressGeneric->sa_family) {
case AF_INET: {
struct sockaddr_in *ip4;
char dest[INET_ADDRSTRLEN];
ip4 = (struct sockaddr_in *) [myData bytes];
addressString = [NSString stringWithFormat: #"IP4: %s", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest)];
}
break;
case AF_INET6: {
struct sockaddr_in6 *ip6;
char dest[INET6_ADDRSTRLEN];
ip6 = (struct sockaddr_in6 *) [myData bytes];
addressString = [NSString stringWithFormat: #"IP6: %s", inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest)];
}
break;
}
NSLog(#"%#", addressString);
}

Get IP address of the current Wi-Fi access point on a iPhone?

I am trying to connect from my iPhone to a socket server running on the same network on my computer. How can I get the local IP address of the computer that is running the socket server?
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
- (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] isEqualToString:#"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;
}
Your server needs to broadcast itself using the mDNS protocol.
Then on the iPhone, you can simply use gethostbyname to get the IP address. You also have a specific API for that: DNS Service Discovery C Reference.

Is there a way to find out if an IP address belongs to an iPhone?

I am trying to find a simple way to check if an IP address belongs to an iPhone.
A solution that I can imagine is to use nmap to determine the operating
system of the specified IP address and then check whether it's iOS..
Is this a right way? Otherwise, could anyone suggest me an alternative way?
Thank you,
Thanasis
Looks like nmap does fingerprint iOS.
We can get the IP address by this code:
- (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] isEqualToString:#"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;
}

Find IP address in iphone

I want to find IP address in an application. I am able to find it. But, problem is, it works fins in iphone os 2.0 or so. But, in iphone os 3.0 it is giving me a warning:
warning: no '+currentHost' method found
warning: (Messages without a matching method signature)
I am using this code, and it works fine with os version 2.0.
-(NSString*)getAddress {
char iphone_ip[255];
strcpy(iphone_ip,"127.0.0.1"); // if everything fails
NSHost* myhost = [NSHost currentHost];
if (myhost)
{
NSString *ad = [myhost address];
if (ad)
strcpy(iphone_ip,[ad cStringUsingEncoding: NSISOLatin1StringEncoding]);
}
return [NSString stringWithFormat:#"%s",iphone_ip];
}
How to find IP address in iphone os 3.0 or greater os version?
Thanks in advance.
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
// retun the host name
+ (NSString *)hostname
{
char baseHostName[256];
int success = gethostname(baseHostName, 255);
if (success != 0) return nil;
baseHostName[255] = '\0';
#if !TARGET_IPHONE_SIMULATOR
return [NSString stringWithFormat:#"%s.local", baseHostName];
#else
return [NSString stringWithFormat:#"%s", baseHostName];
#endif
}
// return IP Address
+ (NSString *)localIPAddress
{
struct hostent *host = gethostbyname([[self hostname] UTF8String]);
if (!host) {herror("resolv"); return nil;}
struct in_addr **list = (struct in_addr **)host->h_addr_list;
return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}
As far as I know there is only one hacky way to do that. You basically open a socket and get its address using POSIX functions. Here is the code I used for this:
http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx
[NSHost currentHost] will also work, but it is deprecated and considered a "Private API" by Apple, so you won't be able to submit your application to App Store.
Put this script on a web server running PHP:
<?php
$ip = getenv("REMOTE_ADDR");
echo $ip;
?>
Call this on the device:
NSURL *scriptURL = [[NSURL alloc] initWithString:#"http://yourserver.com/script.php"];
NSString *ip = [NSString stringWithContentsOfURL: scriptURL encoding:NSASCIIStringEncoding error:nil];
- (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
// it may also be en1 on your ipad3.
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:#"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;
}
Use this to get your IP
If any errors
Please use
#include <ifaddrs.h>
#include <arpa/inet.h>
Getting the IP address is a bit hacky. Are you sure you couldn't live with the device ID (UDID) that is unique to each iPhone and can be retrieved easily via the public API ?
[UIDevice currentDevice].uniqueIdentifier
There is one more way to get the IP address and that too Global IP
NSString* ip=#"http://www.whatismyip.org/";
NSURL *url = [[NSURL alloc] initWithString:ip];
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"%#",ans);
The above site will give you the Global IP.
Just put this in your code and use the IP address where ever you want and also get the location of the user using your app as this gives global IP.
You should have a look to this good project:
uidevice-extension
Specialy this class
Import UIDevice-Reachability.h in your project then try with one of those commands:
NSString *myIp = [UIDevice localIPAddress];
NSString *myIp = [UIDevice localWiFiIPAddress];
NSString *myIp = [UIDevice whatismyipdotcom]; // is using #aamritrao solution
bool success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct sockaddr_dl *dlAddr;
const uint8_t *base;
int i;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
if ( (cursor->ifa_addr->sa_family == AF_LINK)
&& (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type ==IFT_ETHER)
) {
dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
// fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
// fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
printf(" MAC address ");
for (i = 0; i < dlAddr->sdl_alen; i++) {
if (i != 0) {
printf(":");
}
printf("%02x", base[i]);
}
printf("\n");
}
cursor = cursor->ifa_next;
}
}

IPhone : Obtaining Ip address when connected over 3G

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
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.