1 16 package org.apache.commons.net.tftp; 17 18 import java.net.DatagramPacket ; 19 import java.net.InetAddress ; 20 21 42 43 public final class TFTPDataPacket extends TFTPPacket 44 { 45 46 public static final int MAX_DATA_LENGTH = 512; 47 48 49 public static final int MIN_DATA_LENGTH = 0; 50 51 52 int _blockNumber; 53 54 55 int _length; 56 57 58 int _offset; 59 60 61 byte[] _data; 62 63 78 public TFTPDataPacket(InetAddress destination, int port, int blockNumber, 79 byte[] data, int offset, int length) 80 { 81 super(TFTPPacket.DATA, destination, port); 82 83 _blockNumber = blockNumber; 84 _data = data; 85 _offset = offset; 86 87 if (length > MAX_DATA_LENGTH) 88 _length = MAX_DATA_LENGTH; 89 else 90 _length = length; 91 } 92 93 public TFTPDataPacket(InetAddress destination, int port, int blockNumber, 94 byte[] data) 95 { 96 this(destination, port, blockNumber, data, 0, data.length); 97 } 98 99 100 109 TFTPDataPacket(DatagramPacket datagram) throws TFTPPacketException 110 { 111 super(TFTPPacket.DATA, datagram.getAddress(), datagram.getPort()); 112 113 _data = datagram.getData(); 114 _offset = 4; 115 116 if (getType() != _data[1]) 117 throw new TFTPPacketException("TFTP operator code does not match type."); 118 119 _blockNumber = (((_data[2] & 0xff) << 8) | (_data[3] & 0xff)); 120 121 _length = datagram.getLength() - 4; 122 123 if (_length > MAX_DATA_LENGTH) 124 _length = MAX_DATA_LENGTH; 125 } 126 127 138 DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) 139 { 140 data[0] = 0; 141 data[1] = (byte)_type; 142 data[2] = (byte)((_blockNumber & 0xffff) >> 8); 143 data[3] = (byte)(_blockNumber & 0xff); 144 145 if (data != _data) 147 System.arraycopy(_data, _offset, data, 4, _length); 148 149 datagram.setAddress(_address); 150 datagram.setPort(_port); 151 datagram.setData(data); 152 datagram.setLength(_length + 4); 153 154 return datagram; 155 } 156 157 169 public DatagramPacket newDatagram() 170 { 171 byte[] data; 172 173 data = new byte[_length + 4]; 174 data[0] = 0; 175 data[1] = (byte)_type; 176 data[2] = (byte)((_blockNumber & 0xffff) >> 8); 177 data[3] = (byte)(_blockNumber & 0xff); 178 179 System.arraycopy(_data, _offset, data, 4, _length); 180 181 return new DatagramPacket (data, _length + 4, _address, _port); 182 } 183 184 189 public int getBlockNumber() 190 { 191 return _blockNumber; 192 } 193 194 195 public void setBlockNumber(int blockNumber) 196 { 197 _blockNumber = blockNumber; 198 } 199 200 207 public void setData(byte[] data, int offset, int length) 208 { 209 _data = data; 210 _offset = offset; 211 _length = length; 212 213 if (length > MAX_DATA_LENGTH) 214 _length = MAX_DATA_LENGTH; 215 else 216 _length = length; 217 } 218 219 224 public int getDataLength() 225 { 226 return _length; 227 } 228 229 236 public int getDataOffset() 237 { 238 return _offset; 239 } 240 241 246 public byte[] getData() 247 { 248 return _data; 249 } 250 } 251 | Popular Tags |