iOS - Ping with timeout

我的未来我决定 提交于 2019-12-17 10:29:51

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7437643/ios-ping-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!