1. 程式人生 > >微信支付遇到的一個小坑(獲取ip地址的問題)

微信支付遇到的一個小坑(獲取ip地址的問題)

之前測試的時候一直用的無線網,也沒有發現不對頭。後來發現用手機資料流量的時候,一直提示“支付失敗”。

網上查了查才知道原來是獲取手機ip地址的問題。有位仁兄的部落格裡曾經提過把ip地址換成固定的“192.168.1.1”就可以解決了,本人親自測試過,這個解決方法可以,但是總覺

得不太好(如果可以寫成固定的,微信幹嘛還需要我們去獲取ip地址)。

這是我從網上找到的比較好的獲取ip地址方法

#include <ifaddrs.h>

#include <arpa/inet.h>

#include <net/if.h>

#define IOS_CELLULAR    @

"pdp_ip0"

#define IOS_WIFI        @"en0"

#define IOS_VPN         @"utun0"

#define IP_ADDR_IPv4    @"ipv4"

#define IP_ADDR_IPv6    @"ipv6"


#pragma mark---------getipadress

+ (NSString *)getIPAddress:(BOOL)preferIPv4

{

NSArray *searchArray = preferIPv4 ?

@[IOS_VPN@"/"IP_ADDR_IPv4, IOS_VPN@"/"IP_ADDR_IPv6,

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

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

NSDictionary *addresses = [self

getIPAddresses];

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

            }

conststructsockaddr_in *addr = (conststructsockaddr_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;

if(addr->sin_family == AF_INET) {

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

                        type = IP_ADDR_IPv4;

                    }

                } else {

conststructsockaddr_in6 *addr6 = (conststructsockaddr_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 [addresses count] ? addresses : nil;

}

使用的時候直接呼叫  : [self getIPAddress:YES];就行了