I'd like to write a function that checks whether a hostname is reachable on a specific port. So, something like:
func isReachable(hostname: String, port: Int, completion: (Bool) -> ()) {
// …
}
or, if possible:
func isReachable(hostname: String, port: Int) -> Bool {
// …
}
I've tried extending a swift implementation of Apple's Reachability
utility with help from this excellent answer to come up with the following:
public class func reachabilityForHostname(hostname: String, port: Int) -> Reachability? {
var address = sockaddr_in()
address.sin_len = UInt8(sizeofValue(address))
address.sin_family = sa_family_t(AF_INET)
address.sin_addr = in_addr(string: hostname)
address.sin_port = UInt16(9000).bigEndian
let ref = withUnsafePointer(&address) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
return Reachability(reachabilityRef: ref)
}
The problem is that the reachability object I'm creating here always displays as reachable (as long as my network is connected)—so it essentially doesn't actually check that the specific hostname/port is running (I'm trying to see if a server is running on http://localhost:9000).
I've read that Reachability
might not actually be the way to go—as it only checks if an outward connection could be made to the specified host (not guaranteeing that the host is actually online).
Having said all that, my question is simply—what are my options if I would like to check if a specific host (say localhost) has a server running on a specific port?