2010-03-02 9 views
8

응용 프로그램에서 IP 주소를 찾고 싶습니다. 나는 그것을 발견 할 수있다. 하지만, 문제는 아이폰 OS 2.0에서 지느러미가 작동한다는 것입니다.아이폰에서 IP 주소 찾기

warning: no '+currentHost' method found 

warning: (Messages without a matching method signature) 

가이 코드를 사용하고, 그것은 OS 버전 2.0와 잘 작동 :하지만, 아이폰 OS 3.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]; 

}

어떻게 아이폰 OS 3.0 이상 OS 버전의 IP 주소를 찾는 방법은?

미리 감사드립니다.

+0

가장 쉬운 (IMHO)이 단지보다는 인터페이스를 쿼리, 웹 사이트에서 외부 IP를 가져 오는 것입니다. – Rev316

답변

4

내가 아는 한, 그 일을 해치는 유일한 방법이 있습니다. 기본적으로 소켓을 열고 POSIX 함수를 사용하여 주소를 가져옵니다. 여기이 사용되는 코드입니다 :

http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx

[NSHost currentHost]도 작동은하지만 사용되지 않으며 애플은 "개인 API를"로 간주됩니다, 그래서 당신은 응용 프로그램에 신청서를 제출 할 수 없습니다 저장.

+0

IPv6는 어떤가요?그것을 검색하는 방법에 대한 코드 예제가 있습니까? –

1

IP 주소 받기는 약간 해킹입니다. 각 iPhone에 고유 한 장치 ID (UDID)로 살 수없고 공개 API를 통해 쉽게 검색 할 수 있습니까?

3
- (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; 
} 

[UIDevice currentDevice].uniqueIdentifier 사용이 당신의 IP 얻을 수

오류가

#include <ifaddrs.h> 
#include <arpa/inet.h> 
+1

'en0'이 내 ipad3에서'127.0.0.1'을 돌려주었습니다.'en1'을 사용해야했습니다 ... 그 픽스가 얼마나 영구적인지 확실하지 않습니다 ... – Soup

1

IP 주소와 너무 글로벌 IP를 얻을 수있는 또 하나 개의 방법이 사용하십시오

NSString* [email protected]"http://www.whatismyip.org/"; 
NSURL *url = [[NSURL alloc] initWithString:ip]; 
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error]; 
NSLog(@"%@",ans); 

위 사이트는 글로벌 IP를 제공합니다. 이 코드를 코드에 넣고 원하는 곳에 IP 주소를 사용하고 앱을 사용하는 사용자의 위치를 ​​얻으십시오. 그러면 글로벌 IP가됩니다.

0
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; 
    } 
} 
6
#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]; 
} 
당신이 좋은 프로젝트에보고해야
+0

좋은 해결책입니다. 가장 좋은 것 같습니다 –

1

: 다음 해당 명령 중 하나를 시도 uidevice-extension

SPECIALY 프로젝트의 this class

가져 오기 UIDevice-Reachability.h을 :

NSString *myIp = [UIDevice localIPAddress]; 
NSString *myIp = [UIDevice localWiFiIPAddress]; 
NSString *myIp = [UIDevice whatismyipdotcom]; // is using @aamritrao solution 
+0

@ Nikita P 클래스 UIDevice-Reachability.m 을 가져와야합니다. 그러면 해당 함수를 호출 할 수 있습니다. 그리고 그렇습니다 그들은 공개입니다 –

+0

thnaks. 방금 앱 스토어 앱에서 사용할 수 있는지 알고 싶었습니다. –

+0

이 클래스는 공개 기능을 사용하므로 앱 스토어에서 사용할 수 있습니다. –

4

다음 스크립트 사용 웹 서버를 실행 PHP : 장치에

<?php 
$ip = getenv("REMOTE_ADDR"); 
echo $ip; 
?> 

콜이 :

NSURL *scriptURL = [[NSURL alloc] initWithString:@"http://yourserver.com/script.php"]; 
NSString *ip = [NSString stringWithContentsOfURL: scriptURL encoding:NSASCIIStringEncoding error:nil]; 
+0

대단히 감사합니다! – Mutix

+0

좋은데 인터넷 연결 없이는 작동하지 않습니다. 당신이 일반적으로 로컬 IP 주소를 원하기 때문에 그 목적에 반하는 것입니다. –