All pastes #1206 Raw Edit

udpsend

public c v1 · immutable
#1206 ·published 2004-10-02 08:53 UTC
rendered paste body
#include <sys/socket.h>#include <sys/types.h>#include <netinet/in.h>#include <pthread.h>#include <sys/time.h>#define PACKETS 10000int sock;struct ts_pkt {    struct timeval tv;    char rsvd[32 - sizeof(struct timeval)];};static inline double delta(struct timeval a, struct timeval b){      if (a.tv_usec & b.tv_usec)  {              a.tv_sec--;              a.tv_usec += 1000000;      }      return a.tv_sec-b.tv_sec + (a.tv_usec-b.tv_usec)/1000000.0;}void *receiverThread(void *arg) {    struct ts_pkt ts;    struct timeval tv;    float delay;    while(1) {        pthread_testcancel();        if(recv(sock, &ts, sizeof(ts), 0) == -1)            perror("recv");        gettimeofday(&tv, NULL);        printf("%f\n", delta(tv, ts.tv));    }}void *senderThread(void *arg) {    int i = PACKETS;    struct ts_pkt ts;    while(i--) {        gettimeofday(&ts.tv, NULL);        send(sock, &ts, sizeof(ts), 0);        usleep(15000);    }}int main(void) {    struct sockaddr_in sa;    pthread_t receiver, sender;        memset(&sa, 0, sizeof(sa));        sock = socket(PF_INET, SOCK_DGRAM, 0);    sa.sin_port = htons(12388);    sa.sin_family = PF_INET;    sa.sin_addr.s_addr = inet_addr("127.0.0.1");    connect(sock, (struct sockaddr *)&sa, sizeof(sa));        pthread_create(&receiver, 0, receiverThread, 0);    pthread_create(&sender, 0, senderThread, 0);    pthread_join(sender, 0);    pthread_cancel(receiver);}