How to implement ping an IP in MacOS Swift?

Hi all, As far as my research, I found there are two ways to ping an IP Address (ipv4 and ipv6) in MacOS in Swift.

  1. SimplePing
  2. Run command line in code like below
    func doPing() {
        let task = Process()
        task.executableURL = URL(fileURLWithPath: "/sbin/ping")
        task.arguments = [ "-c", "4", "10.1.141.100" ]
        let outputPipe = Pipe()
        task.standardOutput = outputPipe
        let outputHandle = outputPipe.fileHandleForReading
        outputHandle.readabilityHandler = { pipe in
            if let ouput = String(data: pipe.availableData, encoding: .utf8) {
                if !ouput.isEmpty {
                    log += ouput
                    print("----> ouput: \(ouput)")
                }
            } else {
                print("Error decoding data: \(pipe.availableData)")
            }
        }
        task.launch()
    }

So which way is better and which way should I implement for the project?

Hi, It all depends on your project requirements and what you want to achieve / learn with it.

method #2 is simply using the macOS installed ping command to perform the ping. (equivalent of running ping from the terminal yourself). method #1 is implementing the said ping command from scratch using sockets and creating the ICMP packet data manually.

If you want to learn more about networking go with #1, if you just want something that works but don't care about how or why #2.

So which way is better … ?

In general, if you have a choice between an API and a command-line tool, use the API. It’s more efficient, supports more platforms, and has a stronger binary compatibility guarantee.

With regards SimplePing, it’s wildly out of date and I haven’t had time to update it )-: So, if you can find a third-party alternative that you like, go for it!

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I tried your function and I'm seeing an error on the outputHandle.readabilityHandler line.

Type of expression is ambiguous without a type annotation

How to implement ping an IP in MacOS Swift?
 
 
Q