Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active September 17, 2016 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/8bfe5b2169a6b7492d2e7889af996ed8 to your computer and use it in GitHub Desktop.
Save mminer/8bfe5b2169a6b7492d2e7889af996ed8 to your computer and use it in GitHub Desktop.
Determines whether an HTTP port is being used by a process.
import Foundation
func isPortInUse(_ port: Int) -> Bool {
// Use netstat to find ports in use then grep for one we're interested in.
// See this solution for piping shell commands: http://stackoverflow.com/a/16650638
let process = Process()
process.launchPath = "/bin/sh"
process.arguments = ["-c", "netstat -an | grep '\\b\(port)\\b' | grep LISTEN"]
process.standardOutput = Pipe()
process.launch()
process.waitUntilExit()
// No error code suggests something was found.
// Any other code suggests that no results were available.
return process.terminationStatus == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment