tags:

views:

2273

answers:

8

I'm trying to find the local ip address using gethostname/gethostbyname but I always get "Unable to Resolve" when doing it.

Why could it be failing? Are there other way to get the local ip address in the iphone?

Thx a lot

+2  A: 
    -(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]; 
     }
Andy Jacobs
I'm just curious, why bother with the C-string at all, as opposed to just using NSString from the beginning?
erikprice
i got the code from an online example i found. i'm not sure why they'd use a C-String
Andy Jacobs
@Andy Jacobs - Could you show us the URL? I'm curious about the why's and how's.
Kriem
http://appsamuck.com/day4.html
Andy Jacobs
this code NSHost* myhost =[NSHost currentHost]; will be rejected by Apple.
Biranchi
Same as `NSString *address = [[NSHost currentHost] address]; return (address ? address : @"127.0.0.1");`. As Biranchi said, `NSHost` is a private class.
JoostK
+2  A: 

I found a solution using gethostname/gethostbyname in the Erica Sadun book. The trick is to append the ".local" suffix to the hostname before calling gethostbyname.

gustavogb
+1  A: 

In addition to the other answers here, I would suggest reviewing the Reachability sample code on the ADC site.

Roger Nolan
A: 

Can you please post the code on how to get the device ip address using gethostname or gethostbyname. It will be great if any one can help me with this i just got stuck with this. PLease help me out. Waiting fr the soonest response

priyank Ranka
You're trying to commet on the original question I believe? Please use "add comment" there in stead of creating a new answer.
Kriem
sorry for adding as answer but anyone who have that code can please share with me
priyank Ranka
A: 

It's worth noting that many carriers (especially outside the "first world") hand out RFC1918 (usually 10.0.0.0/8) addresses and so doing a HTTP request to one of the services could be better (except, of course, that many carriers, out of necessity use multiple public addresses for large NAT pools)

LapTop006
A: 

can tell you first hand that the ".local" solution from gustavogb works. Thanks gustav.

A: 

NSHost is not found in iPhone OS Library, it is present in Mac OS Core Library.

I am getting 2 warnings

"warning: no '+currentHost' method found" "warning: no '-address' method found"

Any way to remove these warnings ???

Biranchi
No way, it is depreciated
krasnyk
+4  A: 

Check out this link.

http://zachwaugh.com/2009/03/programmatically-retrieving-ip-address-of-iphone/

sugar