iOS - Ping with timeout

2019-01-10 19:58发布

I'm using Apple's "Simple Ping" example and it has almost all features that I need, but I don't know where I can set timeout of each packet. It seems that it isn't possible because function that is used to write data to socket doesn't have any timeout parameters. Does anybody have idea to change this app to get ability to set timeout like in windows ping command? By timeout I mean time for each packet sent to be discarded after waiting for response too long.

Windows ping command - timeout I need to have:

"-w Timeout : Specifies the amount of time, in milliseconds, to wait for the Echo Reply message that corresponds to a given Echo Request message to be received. If the Echo Reply message is not received within the time-out, the "Request timed out" error message is displayed. The default time-out is 4000 (4 seconds)."

Simple Ping code I'm using: http://developer.apple.com/library/mac/#samplecode/SimplePing/Introduction/Intro.html

2条回答
我只想做你的唯一
2楼-- · 2019-01-10 20:23

Apple sample code:

bytesSent = sendto(
    CFSocketGetNative(self->_socket),
    sock,
    [packet bytes],
    [packet length], 
    0, 
    (struct sockaddr *) [self.hostAddress bytes], 
    (socklen_t) [self.hostAddress length]
);

to change the timeout:

CFSocketNativeHandle sock = CFSocketGetNative(self->_socket);
struct timeval tv;
tv.tv_sec  = 0;
tv.tv_usec = 100000; // 0.1 sec
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *)&tv, sizeof(tv));

bytesSent = sendto(
    sock,
    [packet bytes],
    [packet length], 
    0, 
    (struct sockaddr *) [self.hostAddress bytes], 
    (socklen_t) [self.hostAddress length]
);

See Apple's docs: setsockopt

From the above referenced doc:
SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timbal parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

查看更多
混吃等死
3楼-- · 2019-01-10 20:29

for example:

tv.tv_sec = 0;

tv.tv_usec = 1000;

setsockopt(recv_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));

setsockopt(send_sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv,sizeof(struct timeval));

for additional options:

http://developer.apple.com/library/ios/#documentation/system/conceptual/manpages_iphoneos/man2/setsockopt.2.html

查看更多
登录 后发表回答