Swift - Testing a connection to a website and available ports

1.1k Views Asked by At

I haven't been able to find a solid answer to this question anywhere on the internet, and I feel like there has to be a simple answer. I'm trying to test wether I have a connection to specific ip addresses and certain ports with Swift on Mac OS.

I really just want to return true/false if I'm able to connect to a URL, or specific ports associated with it.

Any ideas?

1

There are 1 best solutions below

0
Paul B On

Have a look at the Network framework. It is super powerful and flexible and allows direct access to protocols like TLS, TCP, and UDP for your custom application protocols. It is Swift-ready and easy to use.

import Network

let connection = NWConnection(host: "www.google.com", port: .https, using: .tcp)
connection.stateUpdateHandler = { (newState) in
    switch(newState) {
    case .ready:
    print("Handle connection established")
    case .waiting(let error):
    print("Waiting for network", error.localizedDescription)
    case .failed(let error):
    print("Fatal connection error", error.localizedDescription)
    default:
    break
    }
}
connection.start(queue: .main) // Use some other queue if doing it for real.

The code above will work even in Playground (and fire the stateUpdateHandler at least once). In real app stateUpdateHandler will be called every time the state changes. BTW, URLSession, is built upon this framework.