Source code: com/act365/net/udp/UDPReader.java
1 /*
2 * JSocket Wrench
3 *
4 * Copyright (C) act365.com October 2003
5 *
6 * Web site: http://www.act365.com/wrench
7 * E-mail: developers@act365.com
8 *
9 * The JSocket Wrench library adds support for low-level Internet protocols
10 * to the Java programming language.
11 *
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 2 of the License, or (at your option)
15 * any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
20 * Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along with
23 * this program; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 */
26
27 package com.act365.net.udp ;
28
29 import com.act365.net.* ;
30
31 import java.io.* ;
32
33 /**
34 The class UDPReader reads UDP packets.
35 */
36
37 public class UDPReader {
38
39 /**
40 read() constructs a UDPMessage object from a buffer.
41 */
42
43 public static UDPMessage read( byte[] buffer , int offset , int length ) throws IOException {
44 return read( buffer , offset , length , false , new byte[0] , new byte[0] );
45 }
46
47 /**
48 read() constructs a UDPMessage object from a buffer. When testchecksum is selected,
49 the function assumes the IP header to start at offset=0.
50 */
51
52 public static UDPMessage read( byte[] buffer ,
53 int offset ,
54 int length ,
55 boolean testchecksum ,
56 byte[] source ,
57 byte[] destination ) throws IOException {
58
59 if( length < 8 ){
60 throw new IOException("UDP messages must be at least eight bytes long");
61 }
62
63 UDPMessage message = new UDPMessage();
64
65 message.sourceport = SocketUtils.shortFromBytes( buffer , offset );
66 message.destinationport = SocketUtils.shortFromBytes( buffer , offset + 2 );
67 message.length = SocketUtils.shortFromBytes( buffer , offset + 4 );
68 message.checksum = SocketUtils.shortFromBytes( buffer , offset + 6 );
69
70 if( message.length != length ){
71 throw new IOException("IP and UDP header lengths differ");
72 }
73
74 message.data = new byte[ message.length - 8 ];
75
76 int i = 0 ;
77
78 while( i < message.length - 8 ){
79 message.data[ i ] = buffer[ offset + 8 + i ];
80 ++ i ;
81 }
82
83 if( testchecksum ){
84
85 short checksum = SocketUtils.checksum( source ,
86 destination ,
87 (byte) SocketConstants.IPPROTO_UDP ,
88 message.length ,
89 buffer ,
90 offset );
91
92 if( checksum != 0 ){
93 throw new IOException("Checksum error: " + checksum );
94 }
95 }
96
97 return message ;
98 }
99 }
100