Raheel
Raheel

Reputation: 123

How to calculate time of udp packet sending and receiving

I have a implemented a udp packet sender and receiver. I want to calculate time for transaction, from sender to receiver how much time its taking..

Sender Code:

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;
    }
}

Receiver Code:

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;
}

can anyone please help me that how can i calculate time between this transaction suppose i am sending a packet from Sender to receiver. then how can i calculate that time?

Thanks for always best responses from this forum.. I am looking for your another best response..

Thanks

Rahee.

Upvotes: 1

Views: 3075

Answers (2)

user207421
user207421

Reputation: 310860

Time the round trip for a simple echo request/response from one end and divide by two. It's not a rigorous procedure, as it assumes that the network speed is the same in both directions, but it gives you a ballpark figure.

Upvotes: 0

Sergey Vakulenko
Sergey Vakulenko

Reputation: 1667

I think you need:

1) synchronize your client,server from same timeserver (ntp), to be sure that they have same time.

on client side:

2) get current time and send udp package with timestart

#include <sys/time.h>

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

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

on server side:

3) extract time structure, and compare with current time:

#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);

Upvotes: 1

Related Questions