• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swift 获得手机IP(运营商IP和WiFi的IP)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

        print("手机用户自定义的名称   ===     \(UIDevice.current.name)")
        print("设备名称systemName + iOS版本systemVersion  ==  \(UIDevice.current.systemName + UIDevice.current.systemVersion)")
        print("设备型号(iPhone/ipad/iMac/watch)  ==     \(UIDevice.current.model)")
        print("运营商IP ==      \(deviceIP ?? "本机IP为空")")
        print("wifiIP  ==      \(wifiIP ?? "无线网IP为空")")

  

 

/// 设备运营商IP(联通/移动/电信的运营商给的移动IP)
var deviceIP:String?{
    var addresses = [String]()
    var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while (ptr != nil) {
            let flags = Int32(ptr!.pointee.ifa_flags)
            var addr = ptr!.pointee.ifa_addr.pointee
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                        if let address = String(validatingUTF8:hostname) {
                            addresses.append(address)
                        }
                    }
                }
            }
            ptr = ptr!.pointee.ifa_next
        }
        freeifaddrs(ifaddr)
    }
    return addresses.first
}

 

/// WiFi获得的IP
var wifiIP:String?{
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
    guard getifaddrs(&ifaddr) == 0 else {
        return nil
    }
    guard let firstAddr = ifaddr else {
        return nil
    }
    
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee
        // Check for IPV4 or IPV6 interface
        let addrFamily = interface.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
            // Check interface name
            let name = String(cString: interface.ifa_name)
            if name == "en0" {
                // Convert interface address to a human readable string
                var addr = interface.ifa_addr.pointee
                var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(&addr,socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                address = String(cString: hostName)
            }
        }
    }
    
    freeifaddrs(ifaddr)
    return address
}

  

公网IP : 把数据变为json 在解析

    static func getPublicIP222(backBlock: @escaping ((String)->())){
        DDLOG(message: " Thread = \(Thread.current)")
        
        let ipURL = URL(string: "http://pv.sohu.com/cityjson?ie=utf-8")
        
        var ip: String? = nil
        do {
            if let ipURL = ipURL {
                ip = try String(contentsOf: ipURL, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
            }
        } catch {
        }
        //判断返回字符串是否为所需数据
        if ip?.hasPrefix("var returnCitySN = ") ?? false {
            //对字符串进行处理,然后进行json解析
            //删除字符串多余字符串
            let range = NSRange(location: 0, length: 19)
            if let subRange = Range<String.Index>(range, in: ip ?? "") { ip?.removeSubrange(subRange) }
            let nowIp = (ip as NSString?)?.substring(to: (ip?.count ?? 0) - 1)
            //将字符串转换成二进制进行Json解析
            let data = nowIp?.data(using: .utf8)
            var dict: [String : Any]? = nil
            do {
                if let data = data {
                    dict = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any]
                }
            } catch {
            }
            if let dict = dict {
                print("\(dict)")
            }
            backBlock(dict?["cip"] as? String ?? "")
        }
        backBlock("")
    }

 

类方法

 

/// 获得公网IP
    static func getPublicIP(backBlock: @escaping ((_ ipStr:String)->())){
        let queue = OperationQueue()
        let blockOP = BlockOperation.init {
            if let url = URL(string: "http://pv.sohu.com/cityjson?ie=utf-8") ,
                let s = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
                DDLOG(message: "data:\(s)")
                let subArr = s.components(separatedBy: ":")
                if subArr.count > 1  {
                    let ipStr = subArr[1].replacingOccurrences(of: "\"", with: "")
                    let ipSubArr = ipStr.components(separatedBy: ",")
                    if ipSubArr.count > 0 {
                        let ip = ipSubArr[0].trimmingCharacters(in: CharacterSet.whitespaces)
                        DDLOG(message: "公网IP:\(ip), Thread = \(Thread.current)")
                        DispatchQueue.main.async {
                            backBlock(ip)
                        }
                        return
                    }
                }
            }else {
                DDLOG(message: "获得公网IP URL 转换失败")
            }
            DispatchQueue.main.async {
                JYLogsModel.JYLog(logType: JYLogsModel.JYLogType.errorType, logStr: "获取公网IP失败")
                backBlock("")
            }
            
        }
        queue.addOperation(blockOP)
    }

  

 

    /// 获取当前设备IP
    static func getOperatorsIP() -> String? {
        var addresses = [String]()
        var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
        if getifaddrs(&ifaddr) == 0 {
            var ptr = ifaddr
            while (ptr != nil) {
                let flags = Int32(ptr!.pointee.ifa_flags)
                var addr = ptr!.pointee.ifa_addr.pointee
                if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                    if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String(validatingUTF8:hostname) {
                                addresses.append(address)
                            }
                        }
                    }
                }
                ptr = ptr!.pointee.ifa_next
            }
            freeifaddrs(ifaddr)
        }
        return addresses.first
    }
    
 

  

 //获取本机无线局域网ip
    static func getWifiIP() -> String? {
        
        var address: String?
        var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
        guard getifaddrs(&ifaddr) == 0 else {
            return nil
        }
        guard let firstAddr = ifaddr else {
            return nil
        }
        
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let interface = ifptr.pointee
            // Check for IPV4 or IPV6 interface
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                // Check interface name
                let name = String(cString: interface.ifa_name)
                if name == "en0" {
                    // Convert interface address to a human readable string
                    var addr = interface.ifa_addr.pointee
                    var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(&addr,socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostName)
                }
            }
        }
        
        freeifaddrs(ifaddr)
        return address
    }

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
swifthttppostjson+登录发布时间:2022-07-13
下一篇:
iOSswift中比较模型数组是否相等发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap