7 #include <sys/socket.h>
18 4 bytes CRC32 (made only of data)
25 /* packet = data to transmit
26 * len = length of data
27 * addr = recipient's address
28 * sender = sender's (my) ID
29 * recipient = recipient's ID
33 void send_packet(char *packet
,int len
,const struct sockaddr
* addr
,int sender
,int recipient
)
35 unsigned long crc
=crc32((unsigned char *)packet
,len
);
36 if (!p
) p
=mem_alloc(len
+12);
37 else if (len
> alloc_len
) {
38 p
=mem_realloc(p
,len
+12);
41 if (!p
)return; /* not enough memory */
42 memcpy(p
+12,packet
,len
);
43 p
[0]=(char)(crc
& 0xff);crc
>>=8; /* CRC 32 */
44 p
[1]=(char)(crc
& 0xff);crc
>>=8;
45 p
[2]=(char)(crc
& 0xff);crc
>>=8;
46 p
[3]=(char)(crc
& 0xff);
48 p
[4]=(char)(sender
& 0xff);sender
>>=8; /* sender */
49 p
[5]=(char)(sender
& 0xff);sender
>>=8;
50 p
[6]=(char)(sender
& 0xff);sender
>>=8;
51 p
[7]=(char)(sender
& 0xff);
53 p
[8]=(char)(recipient
& 0xff);recipient
>>=8; /* recipient */
54 p
[9]=(char)(recipient
& 0xff);recipient
>>=8;
55 p
[10]=(char)(recipient
& 0xff);recipient
>>=8;
56 p
[11]=(char)(recipient
& 0xff);
58 sendto(fd
,p
,len
+12,0,addr
,sizeof(*addr
));
62 /* packet = buffer for received data
63 * max_len = size of the buffer
64 * addr = sender's address is filled in
65 * addr_len = size of addr
66 * sender_server = check
67 * recipient = recipient's (my) ID
68 * sender = if !NULL sender's ID
71 /* returns: -1 on error
72 length of received data (data! not CRC nor sender's/recipient's ID
74 int recv_packet(char *packet
,int max_len
,struct sockaddr
* addr
,int *addr_len
,int sender_server
,int recipient
,int *sender
)
76 1=check if sender is 0 (server)
77 0=don't check sender's ID
78 recipient: recipient's id
79 server has: sender_server 0, recipient 0
80 client has: sender_server 1, recipient my_id
87 if (!p
) p
=mem_alloc(max_len
+12);
88 else if (max_len
> alloc_len
) {
89 p
=mem_realloc(p
,max_len
+12);
92 if (!p
)return -1; /* not enough memory */
93 retval
=recvfrom(fd
,p
,max_len
+12,0,addr
,(unsigned int *)addr_len
);
98 memcpy(packet
,p
+12,max_len
);
99 crc
=p
[0]+(p
[1]<<8)+(p
[2]<<16)+(p
[3]<<24);
100 s
=p
[4]+(p
[5]<<8)+(p
[6]<<16)+(p
[7]<<24);
101 if (sender
)*sender
=s
;
102 r
=p
[8]+(p
[9]<<8)+(p
[10]<<16)+(p
[11]<<24);
103 if (retval
==-1)return -1;
104 if (crc
!=crc32((unsigned char *)packet
,retval
-12))return -1;
105 if (r
!=recipient
)return -1;
106 if (sender_server
&&s
)return -1;
110 /* free packet buffer, called only when terminating */
111 void free_packet_buffer() {