2012-06-05 155 views
1

我已經實現了一個udp數據包發送器和接收器。 我要計算時間的交易,從發送端到接收端多少時間其採取..如何計算udp數據包發送和接收的時間

發件人代碼:

void senderFunc() { 
/*some other code */ 
if((s1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) 
    error_handler("\nERROR: in Socket\n"); 
    memset((char *) &me, 0, sizeof(me)); 
    me.sin_family = AF_INET; 
    me.sin_port = PORT; 
    if (inet_aton(G_IP, &me.sin_addr)==0) 
    { 
     fprintf(stderr, "inet_aton() failed\n"); 
     exit(1); 
    } 
    printf("\Tick - %d : %s",cntr++,str); 
    sprintf(b1, "%s",str); // Some Information in b1 buffer to transfer 
    if(sendto(s1, b1, sizeof(b1),0,(struct sockaddr *) &me,n)==-1) 
    error_handler("\nERROR: in sendto()\n"); 
    close (s1); 
    return; 
    } 
} 

接收器代碼:

int receiverFunc() { 
    struct sockaddr_in other, me; 
    int s2, n, i = 1; 
    char b2[BUFLEN];//, b2[BUFLEN]; 
    s2 = socket(AF_INET, SOCK_DGRAM,0); 
    me.sin_family = AF_INET; 
    me.sin_port = PORT; 
    me.sin_addr.s_addr = htonl(INADDR_ANY); 
    bind(s2,(struct sockaddr *)&me, sizeof(me)); 
    n=sizeof(other); 
    int incr = 0; 
    while (i){ 
     recvfrom (s2,b2,BUFLEN,0,(struct sockaddr *) &other, &n); 
     printf ("\nSubnet 2: Tick - %d : %s",incr++, b2); 
    } 
    return 0; 
} 

誰能請幫助我,我如何計算此事務之間的時間假設我正從發件人發送數據包到接收者。那我該如何計算那個時間?

感謝這個論壇總是最好的迴應。我正在尋找您的另一最好的迴應..

感謝

Rahee。

+0

寄件人和收件人在同一臺機器上嗎? –

+0

@Raheel請務必接受最有幫助的答案。 – jncraton

回答

1

我想你需要:

1)同步你的客戶,從同一時間服務器(NTP服務器),以確保它們具有同一時間。

在客戶端:

2)獲得當前時間和與timestart

#include <sys/time.h> 

struct timeval timestart; 
gettimeofday(&timestart, NULL); 

... 
//put timestart to your buffer 
... 

在服務器側發送UDP包:

3)提取時間結構,並且與當前時間進行比較:

#include <sys/time.h> 

... 
//get timestart from your buffer 
... 

struct timeval timeend; 
gettimeofday(&timeend, NULL); 

long diff_msec = (timestart.tv_sec - timeend.tv_sec)/1000 + (timestart.tv_usec - timeend.tv_usec); 
0

來自簡單回聲請求/響應的往返時間一端和二分之一。這不是一個嚴格的程序,因爲它假設網絡速度在兩個方向上都是相同的,但是它給了你一個球場數字。

+0

Sergey Vakulenko謝謝你的回覆。 – Raheel

+0

但是如何在兩臺機器上同步時間?因爲我正在使用離線系統,兩臺計算機上都沒有可用的互聯網連接...在這種情況下可以同步嗎? – Raheel

+0

@Raheel你不需要在兩臺機器上同步時間。您只需要請求發送/響應接收端的開始時間和結束時間。這是衡量往返而非單向的整點。 – EJP