naptics / PlainPing

a very plain ping interface in swift
MIT License
60 stars 21 forks source link

100 ping requests got only several replies #18

Closed jflyup closed 6 years ago

jflyup commented 6 years ago

I want to ping a host 100 times, so I use the code below:

for _ in 1...100 {
    PlainPing.ping("192.168.199.186", withTimeout: 10.0, completionBlock: { (timeElapsed:Double?, error:Error?) in
        print("completed")
    })
}

but got only <10 replies, the wireshark shows it did send and receive 100 icmp packets. What should I do for this scenario?

seeppp commented 6 years ago

Try to send the request in serial order, pinging in parallel is not implemented and doesn't make sense IMO. The route of the second request and further will be the same if you call it close to each other. Ping should be used to determine a host is up or down.

But to accomplish a loop, or similar, use recursion:

var pings:[String] = []

@IBAction func pingButtonPressed(_ sender: UIButton) {
    pings = ["www.google.com", "www.apple.com"]
    pingNext()
}

func pingNext() {
    guard pings.count > 0 else {
        return
    }

    let ping = pings.removeFirst()
    PlainPing.ping(ping, withTimeout: 1.0, completionBlock: { (timeElapsed:Double?, error:Error?) in
        if let latency = timeElapsed {
            print("\(ping) latency (ms): \(latency)")
        }
        if let error = error {
            print("error: \(error.localizedDescription)")
        }
        self.pingNext()
    })
}
jflyup commented 6 years ago

Thanks for the reply, but concurrent ping means something to me, so can I put lots of PlainPing in a GCD queue to achieve that?

seeppp commented 6 years ago

To put every request in another thread should do the trick. But whats your use case? measure the bandwidth or latency, or flooding the server? With PlainPing you cannot specify the packet size of the ping-request, so the results wouldn't be accurate.

I think you're better with another library, this lib means to be plain ;-)

jflyup commented 6 years ago

Yes, I modified the packet size and use it to measure the bandwidth, so it's the case. Anyway, thanks for your project!