Search code examples
swiftmacoscocoatelnet

macOS - Use `Process` to telnet to an IP address and pass commands


I'm developing a macOS app where I need to connect using telnet to a device and send commands to it.

(BTW, I'm connecting to a Roku)

This is as far as I got

func telnet(to host: String, port: String) {
    let process = Process()
    let pipe = Pipe()

    process.executableURL = URL(fileURLWithPath: "/usr/local/bin/telnet")
    process.arguments = [host, port]
    process.standardOutput = pipe

    do {
        try process.run()
    } catch {
        return
    }

    let resultData = pipe.fileHandleForReading.readDataToEndOfFile()
    let result = String (data: resultData, encoding: .utf8) ?? ""
    print(result)
}

telnet(to: "10.0.1.11", port: "8080")

The problem is that the Process is closed immediately. I need to leave the Process open and somehow send commands to the device and then close the connection.

So those are my questions:

  1. How can I leave the Process running?
  2. How can I send commands to the device through the telnet connection?

Solution

  • Your best bet will be to avoid using Process and make a network connection directly from your application. (This will also free you from your dependency on /usr/local/bin/telnet, which is not present in a clean install of macOS.)

    The SwiftSocket pod looks like an excellent way of doing this. The "Client socket example" in the documentation appears to cover most of your questions.