Last active
September 17, 2016 19:33
-
-
Save mminer/8bfe5b2169a6b7492d2e7889af996ed8 to your computer and use it in GitHub Desktop.
Determines whether an HTTP port is being used by a process.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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