jefenater
jefenater

Reputation: 5

How to display output of a function without [ ] brackets?

I'm trying to write a simple app to execute system commands to use the MacOS "Ping" function. I'm trying to essentially execute the command "ping -c 1 -S ethernetIP www.google.com"

I want the system to ping google.com one time through the ethernet adapter specifically and provide the ping results.

When I tie the EthernetIP() and outPing() functions to a button and click it I get the following output:

["17.104.78.250"]

ping: bind: Can't assign requested address [""]

I see that the EthernetIP() function is producing the system ethernet interface IP address in brackets [ ]. This appears to cause the ping function to malfunction as what is being fed into the pingOut() function seems to be:

"ping -c 1 -S ["17.104.78.250"] www.google.com"

I'd like it to feed the shell ping command this line instead:

"ping -c 1 -S 17.104.78.250 www.google.com"

How can I have this string from the ethernet IP query not include the brackets and quotation marks when I reference it in outPing() ?

import Foundation

func runCmd(cmd : String, args : String...) -> ([String]) {

var output : [String] = []

let task = Process()
task.launchPath = cmd
task.arguments = args

let outpipe = Pipe()
task.standardOutput = outpipe

task.launch()

let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
    string = string.trimmingCharacters(in: .newlines)
    output = string.components(separatedBy: "\n")
}

task.waitUntilExit()

return (output)

}

func EthernetIP()  {
let eIP = runCmd(cmd: "/bin/bash", args: "-c", "ipconfig getifaddr en0")
print(eIP)

}

func outPing() {

let pingip = runCmd(cmd: "/sbin/ping", args: "-c 1", "-S", "\(eIP)", "www.google.com" )
print(pingip)

}

Upvotes: 0

Views: 320

Answers (1)

vadian
vadian

Reputation: 285072

I see that the EthernetIP() function is producing the system ethernet interface IP address in brackets [ ]

You do that because you declare the return value as array ([String]) and split the output into paragraphs in the line

output = string.components(separatedBy: "\n")

If you don't want an array write

func runCmd(cmd : String, args : String...) -> String {

    let task = Process()
    task.launchPath = cmd
    task.arguments = args

    let outpipe = Pipe()
    task.standardOutput = outpipe

    task.launch()

    let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
    guard let string = String(data: outdata, encoding: .utf8) else { return ""}
    let output = string.trimmingCharacters(in: .newlines)
    task.waitUntilExit()

    return output
}

Upvotes: 1

Related Questions