1

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?

Community
  • 1
  • 1
pxlshpr
  • 986
  • 6
  • 15
  • 1
    Why not use something like [SwiftSocket](https://github.com/swiftsocket/SwiftSocket) with an appropriate timeout? You'll get a msg back either good or bad and you can close the socket and then do what your app need to do for either is avail or not. – hrbrmstr Aug 29 '15 at 01:48
  • Ah man, that was exactly what I was after. Please answer this question with your comment so I can mark it as correct :) – pxlshpr Aug 29 '15 at 03:22

0 Answers0