Source code: com/act365/net/icmp/ICMPWriter.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.icmp ;
28
29 import com.act365.net.*;
30
31 /**
32 ICMPWriter writes ICMPMessage objects to a byte stream.
33 */
34
35 public class ICMPWriter {
36
37 short identifier ;
38
39 short counter ;
40
41 /**
42 Creates a writer to write to DatagramPacket objects.
43 The identifier will appear in the transmitted datagram packet
44 in modified form in order to enable any reply to be associated
45 with the sender. Typically, the field might be populated with
46 a short generated from the hash code of the transmitting object.
47 */
48
49 public ICMPWriter( short identifier ){
50 this.identifier = identifier ;
51 counter = 0 ;
52 }
53
54 static byte[] write( ICMPMessage message ){
55
56 byte[] buffer = new byte[ message.data.length + 8 ];
57
58 buffer[0] = message.type ;
59 buffer[1] = message.code ;
60 buffer[2] = (byte)( message.checksum >>> 8 );
61 buffer[3] = (byte)( message.checksum & 0xff );
62 buffer[4] = (byte)( message.identifier >>> 8 );
63 buffer[5] = (byte)( message.identifier & 0xff );
64 buffer[6] = (byte)( message.sequence_number >>> 8 );
65 buffer[7] = (byte)( message.sequence_number & 0xff );
66
67 int i = 7 ;
68
69 while( ++ i < buffer.length ){
70 buffer[i] = message.data[i-8];
71 }
72
73 return buffer ;
74 }
75
76 /**
77 Builds a full ICMPMessage object and writes it to a buffer.
78 */
79
80 public byte[] write( byte type ,
81 byte code ,
82 byte[] data )
83 {
84 ICMPMessage message = new ICMPMessage();
85
86 message.type = type ;
87 message.code = code ;
88 message.checksum = 0 ;
89 message.identifier = identifier ;
90 message.sequence_number = counter ++ ;
91 message.data = data ;
92
93 message.checksum = SocketUtils.checksum( write( message ) , 8 + data.length , 0 );
94
95 return write( message );
96 }
97 }
98