10 #include <sys/socket.h>
11 #include <netinet/in.h>
19 int new_packet(short type
, char *packet
)
21 int id
= (time(NULL
) ^ (rand() * 1024*1024));
23 *(short *)(packet
+ 0) = ntohs(0x9012);
24 *(short *)(packet
+ 2) = ntohs(type
);
25 *(int *)(packet
+ 6) = ntohl(id
);
30 int send_packet(int sockfd
, int dest_ip
, int dest_port
, char *packet
, int len
)
32 struct sockaddr_in addr
;
34 *(short *)(packet
+ 4) = ntohs(len
);
36 memset(&addr
, 0, sizeof(addr
));
37 addr
.sin_family
= AF_INET
;
38 *(int*)&addr
.sin_addr
= htonl(dest_ip
);
39 addr
.sin_port
= htons(dest_port
);
40 if (sendto(sockfd
, packet
, len
, 0, (void *) &addr
, sizeof(addr
)) < 0)
48 int read_packet(int sockfd
, char *packet
)
50 struct sockaddr_in addr
;
51 int alen
= sizeof(addr
);
52 memset(&addr
, 0, sizeof(addr
));
53 return recvfrom(sockfd
, packet
, 1400, 0, (void *) &addr
, &alen
);
56 void dump_packet(char *packet
, FILE *stream
)
58 if (htons(*(short *)(packet
+ 0)) != 0x9012)
60 fprintf(stream
, "Invalid packet identifier %x\n", htons(*(short *)(packet
+ 0)));
63 fprintf(stream
, "Control packet:\n");
64 fprintf(stream
, " Type: %d\n", htons(*(short *)(packet
+ 2)));
65 fprintf(stream
, " Length: %d\n", htons(*(short *)(packet
+ 4)));
66 fprintf(stream
, " Identifier: %x\n", htonl(*(int *)(packet
+ 6)));
67 fprintf(stream
, "\n");