iOS SimplePing delegates

2019-09-22 03:26发布

I am using SimplePing to scan my LAN. I am trying to ping all the availables IPs on my network so I am firing the ping fore the first host and then the delegates are firing the ping again for the next host. The issue here is that when a host is unreachable no delegate is firing. I am using the following delegates:

- (void)simplePing:(SimplePing *)pinger didStartWithAddress:(NSData *)address;
- (void)simplePing:(SimplePing *)pinger didFailWithError:(NSError *)error;
- (void)simplePing:(SimplePing *)pinger didSendPacket:(NSData *)packet;
- (void)simplePing:(SimplePing *)pinger didFailToSendPacket:(NSData *)packet error:(NSError *)error;
- (void)simplePing:(SimplePing *)pinger didReceivePingResponsePacket:(NSData *)packet;
 - (void)simplePing:(SimplePing *)pinger didReceiveUnexpectedPacket:(NSData *)packet;

So in case of success the didReceivePingPacket is firing the next ping BUT in case of fail not of the above delegates is exetuted.

I tried to decrease the ping timeout in order to fire the didFailWithError delegate with this but it seems is not working. So my question is: Is there any way to know when a host is unreachable using SimplePing?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-22 04:16

The link you provided doesn't set the "ping timeout", it sets the send timeout. A ping timeout doesn't exist in this context, I'm afraid, as the network operation was completed successfully, you just didn't get a response back. You'll have to check for this timeout condition yourself.

The way I would do it is when you send out a packet (in the didSendPacket: method), fire up a NSTimer. If the method didReceivePingResponsePacket: is executed before the timer runs out, the ping obviously did return and you can invalidate the timer; if however your timer fires before you receive a response packet, you should assume a "ping timeout" occurred.

In code it would look something like this (I'm writing this out of my head, so... double check syntax, place the variables and methods in appropriate places, ... the code should demonstrate the principle, though):

const PING_TIMEOUT = 1.0f
pingTimer: NSTimer = nil;

- (void)pingNextHost {
    // set up the next host IP address, whatever needs to be done
    simplePing.sendPingWithData:(<some NSData>);
}

- (void)simplePing:(SimplePing *)pinger didSendPacket:(NSData *)packet {
    pingTimer = [NSTimer scheduledTimerWithTimeInterval:PING_TIMEOUT target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
}

- (void)simplePing:(SimplePing *)pinger didReceivePingResponsePacket:(NSData *)packet {
    NSLog(@"got response packet, host reachable");
    // Invalidate timer
    [pingTimer invalidate];
    // Move to next host
    [self pingNextHost];
}

- (void):timerFired(NSTimer *)timer {
    NSLog(@"ping timeout occurred, host not reachable");
    // Move to next host
    [self pingNextHost];
}
查看更多
登录 后发表回答