ios開發 iphone中擷取網卡地址和ip地址

來源:互聯網
上載者:User

// 通過網域名稱擷取IP地址

+ (NSString *)IPAdressFromDomain:(NSString *)host

{

  structhostent *hostent = gethostbyname([hostUTF8String]);

  if (!hostent) {

    herror("resolv");

    returnNULL;

  }

  structin_addr **list = (structin_addr **)hostent->h_addr_list;

  NSString *addressString = [NSStringstringWithCString:inet_ntoa(*list[0])encoding:NSUTF8StringEncoding];

  return addressString;

}



// 擷取本機IP地址

+ (NSString *)getIPAddress:(BOOL)preferIPv4

{

  /*

   * 此處可以選擇是優先返回wifi的還是cell的,或者ipv4的還是ipv6的

   */

  NSArray *searchArray = preferIPv4 ?

  @[IOS_WIFI @"/"IP_ADDR_IPv4, IOS_WIFI@"/" IP_ADDR_IPv6,IOS_CELLULAR @"/"IP_ADDR_IPv4, IOS_CELLULAR@"/" IP_ADDR_IPv6] :

  @[IOS_WIFI @"/"IP_ADDR_IPv6, IOS_WIFI@"/" IP_ADDR_IPv4,IOS_CELLULAR @"/"IP_ADDR_IPv6, IOS_CELLULAR@"/" IP_ADDR_IPv4] ;

  

  NSDictionary *addresses = [selfgetIPAddresses];

  NSLog(@"addresses: %@", addresses);

  

  __blockNSString *address;

  [searchArray enumerateObjectsUsingBlock:^(NSString *key,NSUInteger idx, BOOL *stop)

   {

     address = addresses[key];

     if(address) *stop =YES;

   } ];

  return address ? address :@"0.0.0.0";

}


+ (NSDictionary *)getIPAddresses

{

  NSMutableDictionary *addresses = [NSMutableDictionarydictionaryWithCapacity:8];

  

  // retrieve the current interfaces - returns 0 on success

  structifaddrs *interfaces;

  if(!getifaddrs(&interfaces)) {

    // Loop through linked list of interfaces

    structifaddrs *interface;

    for(interface=interfaces; interface; interface=interface->ifa_next) {

      if(!(interface->ifa_flags &IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {

        continue;// deeply nested code harder to read

      }

      conststruct sockaddr_in *addr = (conststruct sockaddr_in*)interface->ifa_addr;

      char addrBuf[MAX(INET_ADDRSTRLEN,INET6_ADDRSTRLEN) ];

      if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {

        NSString *name = [NSStringstringWithUTF8String:interface->ifa_name];

        NSString *type =nil;

        if(addr->sin_family ==AF_INET) {

          if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {

            type = IP_ADDR_IPv4;

          }

        } else {

          conststruct sockaddr_in6 *addr6 = (conststruct sockaddr_in6*)interface->ifa_addr;

          if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {

            type = IP_ADDR_IPv6;

          }

        }

        if(type) {

          NSString *key = [NSStringstringWithFormat:@"%@/%@", name, type];

          addresses[key] = [NSStringstringWithUTF8String:addrBuf];

        }

      }

    }

    // Free memory

    freeifaddrs(interfaces);

  }

  return [addressescount] ? addresses : nil;

}




這是擷取網卡的硬體地址的代碼,如果無法編譯通過,記得把下面的這幾個標頭檔加上把。

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#pragma mark MAC addy
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to mlamb.
- (NSString *) macaddress
{
    int                    mib[6];
    size_t                len;
    char                *buf;
    unsigned char        *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl    *sdl;
   
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
   
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
   
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
   
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
   
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
   
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    // NSString *outstring = [NSString stringWithFormat:@"x:x:x:x:x:x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    NSString *outstring = [NSString stringWithFormat:@"xxxxxx", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}

 

 

 

這寫標頭檔是用於擷取ip等系列功能的
#include <arpa/inet.h>
#include <netdb.h>

#include <net/if.h>

#include <ifaddrs.h>
#import <dlfcn.h>
#import "wwanconnect.h//frome apple 你可能沒有哦

#import <SystemConfiguration/SystemConfiguration.h>

 

 

擷取ip地址的代碼有很多

 

這是外網可見的ip地址,如果你在小區的區域網路中,那就是小區的,不是區域網路的內網地址。

- (NSString *) whatismyipdotcom
{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://www.whatismyip.com/automation/n09230945.asp"];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:1 error:&error];
    return ip ? ip : [error localizedDescription];
}

 

這是擷取本地wifi的ip地址

// 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 *) localWiFiIPAddress
{
    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:@"en0"])  // 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和Address的轉換

+ (NSString *) stringFromAddress: (const struct sockaddr *) address
{
    if(address && address->sa_family == AF_INET) {
        const struct sockaddr_in* sin = (struct sockaddr_in*) address;
        return [NSString stringWithFormat:@"%@:%d", [NSString stringWithUTF8String:inet_ntoa(sin->sin_addr)], ntohs(sin->sin_port)];
    }
   
    return nil;
}

+ (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address
{
    if (!IPAddress || ![IPAddress length]) {
        return NO;
    }
   
    memset((char *) address, sizeof(struct sockaddr_in), 0);
    address->sin_family = AF_INET;
    address->sin_len = sizeof(struct sockaddr_in);
   
    int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr);
    if (conversionResult == 0) {
        NSAssert1(conversionResult != 1, @"Failed to convert the IP address string into a sockaddr_in: %@", IPAddress);
        return NO;
    }
   
    return YES;
}
擷取host的名稱
- (NSString *) hostname
{
    char baseHostName[256]; // Thanks, Gunnar Larisch
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '/0';
   
#if TARGET_IPHONE_SIMULATOR
     return [NSString stringWithFormat:@"%s", baseHostName];
#else
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#endif
}
從host擷取地址
- (NSString *) getIPAddressForHost: (NSString *) theHost
{
    struct hostent *host = gethostbyname([theHost UTF8String]);
    if (!host) {herror("resolv"); return NULL; }
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
    return addressString;
}

這是本地host的IP地址
- (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];
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.