How to get the public IP address of the device

前端 未结 9 603
陌清茗
陌清茗 2020-12-29 10:32

I found this sample code to get all local IP addresses, but I don\'t find an easy solution to get the public IP.

A legacy class from Apple allowed to do that ... bu

9条回答
  •  误落风尘
    2020-12-29 11:03

    Thanks @Tarek for his answer

    Here, code in Swift 4 version

    func getPublicIPAddress() -> String {
        var publicIP = ""
        do {
            try publicIP = String(contentsOf: URL(string: "https://www.bluewindsolution.com/tools/getpublicip.php")!, encoding: String.Encoding.utf8)
            publicIP = publicIP.trimmingCharacters(in: CharacterSet.whitespaces)
        }
        catch {
            print("Error: \(error)")
        }
        return publicIP
    }
    

    NOTE1: To get public IP address, we must have external site to return public IP. The website I use is business company website, so, it will be their until the business gone.

    NOTE2: You can made some site by yourself, however, Apple require HTTPS site to be able to use this function.

提交回复
热议问题