
进来接微信支付,后台要传ip地址,so~
首先要导这些头文件
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <math.h> 4 #include <string.h> 5 #include <unistd.h> 6 #include <sys/ioctl.h> 7 #include <sys/types.h> 8 #include <sys/sysctl.h> 9 #include <sys/socket.h> 10 #include <netinet/in.h> 11 #include <netdb.h> 12 #include <arpa/inet.h> 13 #include <sys/sockio.h> 14 #include <net/if.h> 15 #include <net/ethernet.h> 16 #include <errno.h> 17 #include <net/if_dl.h> 18 #include <ifaddrs.h> 19 #include <mach/machine.h>
然后就是方法啦:
1 + (NSString *)getIPAddress
2 {
3 NSString *address = @"error";
4 struct ifaddrs *interfaces = NULL;
5 struct ifaddrs *temp_addr = NULL;
6 int success = 0;
7 // retrieve the current interfaces - returns 0 on success
8 success = getifaddrs(&interfaces);
9 if (success == 0)
10 {
11 // Loop through linked list of interfaces
12 temp_addr = interfaces;
13 while(temp_addr != NULL)
14 {
15 if(temp_addr->ifa_addr->sa_family == AF_INET)
16 {
17 // Check if interface is en0 which is the wifi connection on the iPhone
18 if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
19 {
20 // Get NSString from C String
21 address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
22 }
23 }
24 temp_addr = temp_addr->ifa_next;
25 }
26 }
27 // Free memory
28 freeifaddrs(interfaces);
29 return address;
30 }
我是给放在工具类里面了,哪里要用调哪里~so easy~