有的时候,我们项目上线后,需要根据ip地址去统计不同地区的用户情况,此时IP地址的收取显得尤其重要,一般情况下,在用户登录时去获取用户的ip是准确的,当然实时追踪ip的变化而统计是更安全可靠的。
ip地址长度现在是有区别的,分为IPv4和IPv6.IPv4地址是类似 A.B.C.D 的格式,它是32位,用\".\"分成四段,用10进制表示;而IPv6地址类似X:X:X:X:X:X:X:X的格式,它是128位的,用\":\"分成8段,用16进制表示;可见,IPv6地址空间相对于IPv4地址有了极大的扩充。
IPv4是32位地址长度IPv6是128位地址长度
下面有两个方法,可供使用,如下:
方法一:使用一套C的方法去获取IP地址
IPAddress.h:声明文件
View Code
IPAddress.c:实现文件
View Code
将头文件导入ViewController.m中进行测试
View Code
测试结果:
模拟器上连接wifi:
2016-07-15 16:19:49.187 IP_Test[5674:205359] Name: lo0 MAC: 00:00:00:00:00:00 IP: 127.0.0.12016-07-15 16:19:49.187 IP_Test[5674:205359] Name: en1 MAC: BC:54:36:CC:9C:96 IP: 192.168.0.109
iphone上:
连接wifi时:
2016-07-15 17:32:08.884 IP_Test[4813:2032752] Name: lo0 MAC: 00:00:00:00:00:00 IP: 127.0.0.12016-07-15 17:32:08.885 IP_Test[4813:2032752] Name: pdp_ip0 MAC: 00:00:00:00:00:70 IP: 10.204.102.1362016-07-15 17:32:08.885 IP_Test[4813:2032752] Name: en0 MAC: 02:00:00:00:00:00 IP: 192.168.0.111
使用4G时:
2016-07-15 17:32:44.163 IP_Test[4817:2033214] Name: lo0 MAC: 00:00:00:00:00:00 IP: 127.0.0.12016-07-15 17:32:44.164 IP_Test[4817:2033214] Name: pdp_ip0 MAC: 00:00:00:00:00:70 IP: 10.204.102.136
方法二:使用一套OC的方法去获取IP地址,该方法简单,能实时监测IP地址的变化
stackoverflow参考地址为:
View Code
测试结果:
模拟器上连接wifi:
2016-07-15 16:23:35.864 IP_Test[5718:207702] { "awdl0/ipv6" = "fe80::e863:edff:fe93:a1c2"; "en1/ipv4" = "192.168.0.109"; "en1/ipv6" = "fe80::be54:36ff:fecc:9c96"; "lo0/ipv4" = "127.0.0.1"; "lo0/ipv6" = "fe80::1";}2016-07-15 17:24:12.877 IP_Test[4796:2028704] 0.0.0.0
iphone上:
连接wifi时:
2016-07-15 17:29:22.526 IP_Test[4807:2031207] addresses: { "awdl0/ipv6" = "fe80::6c6a:24ff:fe91:39f7"; "en0/ipv4" = "192.168.0.111"; "en0/ipv6" = "fe80::42d:42b4:82a7:3de8"; "lo0/ipv4" = "127.0.0.1"; "lo0/ipv6" = "fe80::1"; "pdp_ip0/ipv4" = "10.204.102.136";}2016-07-15 17:29:22.527 IP_Test[4807:2031207] 192.168.0.111
使用4G时:
2016-07-15 17:24:12.875 IP_Test[4796:2028704] addresses: { "lo0/ipv4" = "127.0.0.1"; "lo0/ipv6" = "fe80::1"; "pdp_ip0/ipv4" = "10.204.102.136";}2016-07-15 17:24:12.877 IP_Test[4796:2028704] 10.204.102.136
温馨提示:本人进一步做了简单的封装,封装成工具库,支持CocoaPods下载,源码在github上,欢迎大家下载,如果对您有帮助,请给我一个star吧
CocoaPods: pod 'IPTool','~> 1.0.0'
Github: