Checksum in UDP Datagram Socket + java
It is my understanding that the UDP protocol does not define the action to be taken if the data gets corrupted ie the checksum fails. That is our application can make the packet to be retransmitted or let the packet be declared lost....
While implementing Datagram Sockets in java I want to identify if the checksum is correct or not for some packet sent ....
Is there any way in java to do so...
Basically I want that I come to know that this p开发者_开发百科acket has been corrupted while transmission and thus has to be retransmitted....
Thanks a lot
I'd check out the two following classes: CheckedInputStream and Checksum. A checksum should be performed by the machine sending the packet, and the machine receiving the packet should also perform a checksum, and then compare values. At least that's how I've seen it done..
Note: checksum must be included in packet being sent across. Also, since you're checking if the data has been corrupted, ByteArrayInputStream may prove to be useful too. Here's an example.
First you have to add the checksum to the udp message. I assume that the checksum has been put in front on the rest of the message and I assume that calcCheckSum can calculate the checksum.
import java.net.*;
DatagramSocket socket = new DatagramSocket();
byte[] buffer = new byte[256]; // some appropriate size
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String checksum = new String(packet.getData(),0, <some length>);
boolean ok = calcCheckSum(checksum);
The UDP header itself is short and of fixed size (8 bytes):
offset | size | contents |
---|---|---|
0 | 16 bits | source port |
2 | 16 bits | destination port |
4 | 16 bits | length |
6 | 16 bits | checksum |
The checksum algorithm is defined in RFC 768.
So, talking of Java, the DatagramSocket/DatagramPackets should do the checksum calculation and checking.
But it appears they do not. I dug into the implementation classes which still are in com.sun. legacy packages, and they seem to ignore checksum entirely. No computing, no checking.
They also do not send an Exception or other notice to the user about a failure in the checksum. Thus, the answer to the original questions are:
- Java JDK implementation does not handle the UDP checksum at all.
- So, no, in standard Java you cannot identify whether the UDP checksum is correct.
- You'll have to do your own checksumming in the packet payload data instead.
And in the data, it is entirely up to you how you do that.
精彩评论