Skip to content

修复ping时统计异常的问题 #385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 25 additions & 14 deletions protocol/icmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ int ping(const char* host, int cnt) {
static uint16_t seq = 0;
uint16_t pid16 = (uint16_t)getpid();
char ip[64] = {0};
uint32_t start_tick, end_tick;
uint32_t start_tick, end_tick, cur_ping_start_tick;
uint64_t start_hrtime, end_hrtime;
int timeout = 0;
int sendbytes = 64;
Expand Down Expand Up @@ -64,7 +64,9 @@ int ping(const char* host, int cnt) {
icmp_req->icmp_data[i] = i;
}
start_tick = gettick_ms();

while (cnt-- > 0) {
cur_ping_start_tick = gettick_ms();
// NOTE: checksum
icmp_req->icmp_seq = ++seq;
icmp_req->icmp_cksum = 0;
Expand All @@ -78,29 +80,38 @@ int ping(const char* host, int cnt) {
}
++send_cnt;
addrlen = sizeof(peeraddr);
_read_again:
if(gettick_ms() - cur_ping_start_tick >= PING_TIMEOUT) {
// recv timeout, send ping again.
continue;
}

int nrecv = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, &peeraddr.sa, &addrlen);
if (nrecv < 0) {
perror("recvfrom");
continue;
goto _read_again;
}
++recv_cnt;

end_hrtime = gethrtime_us();
// check valid
bool valid = false;
int iphdr_len = ipheader->ihl * 4;
int icmp_len = nrecv - iphdr_len;
if (icmp_len == sendbytes) {
icmp_res = (icmp_t*)(recvbuf + ipheader->ihl*4);
if (icmp_res->icmp_type == ICMP_ECHOREPLY &&
icmp_res->icmp_id == pid16 &&
icmp_res->icmp_seq == seq) {
valid = true;
}
if (icmp_len != sendbytes) {
// not our ping
goto _read_again;
}
if (valid == false) {
printd("recv invalid icmp packet!\n");
continue;

icmp_res = (icmp_t*)(recvbuf + ipheader->ihl*4);
if (icmp_res->icmp_type != ICMP_ECHOREPLY ||
icmp_res->icmp_id != pid16 ||
icmp_res->icmp_seq != seq) {
// not our ping
goto _read_again;
}

end_hrtime = gethrtime_us();
++recv_cnt;

rtt = (end_hrtime-start_hrtime) / 1000.0f;
min_rtt = MIN(rtt, min_rtt);
max_rtt = MAX(rtt, max_rtt);
Expand Down