Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ping a Website or an IP Address (or Check if a Website is Online) using Swift 4?

Tags:

People also ask

How do I ping an IP address in Swift?

ping(host: "google.com", configuration: configuration, queue: DispatchQueue. main) { (ping, error) in print("\(ping)") print("\(error)") } SwiftPing. pingOnce(host: "google.com", configuration: configuration, queue: DispatchQueue. global()) { (response: PingResponse) in print("\(response.

Can you ping a website with an IP address?

In the Command Prompt window, type "ping" followed by the destination — either an IP address or a domain name, then press Enter. The results of the ping will begin to show in the Command Prompt. Each ping test makes four attempts and gives a response for each.

Can you ping a website?

Within the prompt, type "cmd" followed by a space and the IP address or domain name you want to ping. For example, you might type "ping www.example.com" or "ping 127.0. 0.1." Then, press the "enter" key.


I have been searching since yesterday for a simpler solution to just ping a website & check if it returns 200 in Swift.

But all I'm finding are solutions in Objective C.

In Swift, I found some answers like

func pingHost(_ fullURL: String) {
        let url = URL(string: fullURL)

        let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
            if let httpResponse = response as? HTTPURLResponse {
                print(httpResponse.statusCode)
            }
        }

        task.resume()
    }

But when I call it from some other function like

self.pingHost("https://www.google.com")

It gives weird errors like

2018-09-26 12:46:34.076938+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
2018-09-26 12:46:35.082274+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
2018-09-26 12:46:36.083497+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
2018-09-26 12:46:37.083964+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:5 Err:-1 Errno:1 Operation not permitted
2018-09-26 12:46:37.084497+0530 Net Alert[1608:52682] [] nw_resolver_create_dns_service_locked [C1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2018-09-26 12:46:37.087264+0530 Net Alert[1608:52682] TIC TCP Conn Failed [1:0x600003706e80]: 10:-72000 Err(-65563)
2018-09-26 12:46:37.088841+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> HTTP load failed (error code: -1003 [10:-72000])
2018-09-26 12:46:37.088990+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> finished with error - code: -1003

How do I just simply ping in Swift 4 & check if it returns 200?