tftp 服务器

几个月前编写的程序,今日进行了修改,该程序只有服务器端,参考了TFTP协议规范。
几个月前写的,今天改了一下,只有服务器端.
参考: tftp协议规范
tftp uml
TFtpServer.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
 * 创建日期 2004-8-30-11:31:14
 *
 */
package starfire.tftp;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 * <a href="http://www.longen.org/S-Z/details-z/TFTPProtocol.htm">tftp 协议规范 </a>
 * 
 * @author <a href="mailto:starfire@bit.edu.cn">starfire </a>
 *  
 */
public class TFtpServer extends Thread {

    public static final int DEFAULT_PORT = 69;

    private HashMap map = new HashMap();

    private File root;

    private int port = DEFAULT_PORT;

    private DatagramSocket ds;

    private Timer timer = new Timer(true);

    public TFtpServer() {
        this(".");
    }

    public TFtpServer(String rootPath, int port) {
        this(rootPath);
        this.port = port;
    }

    public TFtpServer(String rootPath) {
        this.root = new File(rootPath);
        try {
            this.root = this.root.getCanonicalFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            ds = new DatagramSocket(new InetSocketAddress(port));
        } catch (SocketException e) {
            System.out.println("error when create datagram socket:"
                    + e.getMessage());
            return;
        }
        System.out.println("root path:" + root.getPath());
        byte[] buf = new byte[516];
        DatagramPacket packet = new DatagramPacket(buf, 516);
        while (true) {
            try {
                ds.receive(packet);
                System.out.println("recv packet:");
                TFtpPacketUtil.displayBytes(packet.getData());//
                process(packet);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    protected void process(DatagramPacket packet) {
        try {
            byte[] buf = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), 0, buf, 0, buf.length);
            TFtpPacket tfp = TFtpPacketUtil.decode(buf);
            InetSocketAddress address = new InetSocketAddress(packet
                    .getAddress(), packet.getPort());
            String key = address.getHostName() + ":" + address.getPort();
            System.out.println("key=" + key);
            System.out.println("packet:" + tfp);
            if (tfp.getOperateCode() == TFtpPacket.RRQ
                    || tfp.getOperateCode() == TFtpPacket.WRQ) {
                Client client = new Client(address);
                boolean result = client.doAccept((RWPacket) tfp);
                if (result) {
                    map.put(key, client);
                }
            } else if (tfp.getOperateCode() == TFtpPacket.DATA) {
                Client client = (Client) map.get(key);
                if (client == null) {
                    return;
                }
                boolean result = client.doProcess((DATAPacket) tfp);
                if (result) {
                    map.remove(key);
                    client.destroy();
                }
            } else if (tfp.getOperateCode() == TFtpPacket.ACK) {
                Client client = (Client) map.get(key);
                if (client == null) {
                    return;
                }
                boolean result = client.doProcess((ACKPacket) tfp);
                if (result) {
                    map.remove(key);
                    client.destroy();
                }
            } else if (tfp.getOperateCode() == TFtpPacket.ERROR) {
                System.out.println(tfp);
                Client client = (Client) map.remove(key);
                client.destroy();
            }
        } catch (BadPacketFormatException e) {
            e.printStackTrace();
            System.out.println("recv unknown packet.");
        }
    }

    protected void send(InetSocketAddress address, byte[] data) {
        DatagramPacket packet = new DatagramPacket(data, data.length, address
                .getAddress(), address.getPort());
        try {
            ds.send(packet);
            System.out.println("send packet:");
            TFtpPacketUtil.displayBytes(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Client {
        public static final int DEFAULT_DATA_SIZE = 512;

        public static final int DEFAULT_TIME_OUT = 1000;

        private InetSocketAddress address;

        private String fileName;

        private int block;

        private boolean checked;//上次发送的包已收到回应

        private RandomAccessFile raf;

        private boolean accepted = false;

        private byte[] buf = new byte[DEFAULT_DATA_SIZE];

        private byte[] data;

        private int times = 0;//每几次重发

        private ResendTask task;

        public Client(InetSocketAddress address) {
            this.address = address;
        }

        public void destroy() {
            if (task != null) {
                task.cancel();
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                raf = null;
            }
        }

        /**
         * if accept,return true;else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doAccept(RWPacket packet) {
            this.fileName = packet.getFileName();
            if (accepted) {
                return true;
            }
            if (packet.getOperateCode() == TFtpPacket.RRQ) {
                try {
                    File file = new File(root, fileName);
                    System.out.println(file.getPath() + " " + file.exists());
                    raf = new RandomAccessFile(file, "r");
                    data = new byte[DEFAULT_DATA_SIZE];
                    int size = raf.read(data);
                    DATAPacket dp = new DATAPacket();
                    dp.setBlock(1);
                    if (size != DEFAULT_DATA_SIZE) {
                        byte[] buf = new byte[size];
                        System.arraycopy(data, 0, buf, 0, size);
                        data = buf;
                    }
                    dp.setData(data);
                    data = TFtpPacketUtil.encode(dp);
                    send(address, data);
                    block = 1;
                    task = new ResendTask(address, data);
                    timer.schedule(task, DEFAULT_TIME_OUT);
                } catch (FileNotFoundException e) {
                    System.out
                            .println("file:" + e.getMessage() + " not found.");
                    ERRORPacket ep = new ERRORPacket();
                    ep.setErrorCode(ERRORPacket.FILE_NOT_FOUND_CODE);
                    byte[] data = TFtpPacketUtil.encode(ep);
                    send(address, data);
                    return false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                File file = new File(root, fileName);
                if (file.exists()) {
                    ERRORPacket ep = new ERRORPacket();
                    ep.setErrorCode(ERRORPacket.FILE_EXIST_CODE);
                    ep.setErrorMessage("file:" + fileName + " has exist");
                    byte[] data = TFtpPacketUtil.encode(ep);
                    send(address, data);
                    return false;
                }
                try {
                    file.createNewFile();
                    raf = new RandomAccessFile(file, "rwd");
                } catch (IOException e) {
                    System.out.println("create file:" + fileName + " failed.");
                    ERRORPacket ep = new ERRORPacket();
                    ep.setErrorCode(ERRORPacket.NOT_DEFINED_CODE);
                    byte[] data = TFtpPacketUtil.encode(ep);
                    send(address, data);
                    return false;
                }
                ACKPacket ap = new ACKPacket();
                ap.setBlock(0);
                data = TFtpPacketUtil.encode(ap);
                send(address, data);
                task = new ResendTask(address, data);
                timer.schedule(task, DEFAULT_TIME_OUT);
            }
            accepted = true;
            return accepted;
        }

        /**
         * if transfer end,return true,else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doProcess(ACKPacket packet) {
            if (task != null) {
                task.cancel();
                task = null;
            }
            if (packet.getBlock() == block) {
                try {
                    if (raf == null
                            || raf.length() <= block * DEFAULT_DATA_SIZE) {
                        return true;
                    }
                    raf.seek(block * DEFAULT_DATA_SIZE);
                    int size = raf.read(buf);
                    data = buf;
                    if (size < DEFAULT_DATA_SIZE) {
                        data = new byte[size];
                        System.arraycopy(buf, 0, data, 0, size);
                        raf.close();
                        raf = null;
                    }
                    DATAPacket dp = new DATAPacket();
                    block++;
                    dp.setBlock(block);
                    dp.setData(data);
                    data = TFtpPacketUtil.encode(dp);
                    send(address, data);
                    TFtpPacketUtil.displayBytes(data);
                    task = new ResendTask(address, data);
                    timer.schedule(task, DEFAULT_TIME_OUT);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        /**
         * if transfer end,return true,else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doProcess(DATAPacket packet) {
            if (task != null) {
                task.cancel();
                task = null;
            }
            byte[] data = packet.getData();
            if (packet.getBlock() != block + 1) {
                return false;
            }
            block++;
            ACKPacket ap = new ACKPacket();
            ap.setBlock(block);
            if (data != null) {
                try {
                    raf.write(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (data == null || data.length < DEFAULT_DATA_SIZE) {
                try {
                    raf.close();
                    raf = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            data = TFtpPacketUtil.encode(ap);
            send(address, data);
            task = new ResendTask(address, data);
            timer.schedule(task, DEFAULT_TIME_OUT);
            return packet.getData() == null
                    || packet.getData().length < DEFAULT_DATA_SIZE;
        }

    }

    class ResendTask extends java.util.TimerTask {
        private InetSocketAddress address;

        private byte[] data;

        private int times = 1;

        public ResendTask(InetSocketAddress address, byte[] data) {
            this.address = address;
            this.data = data;
        }
        
        public ResendTask(InetSocketAddress address, byte[] data,int times) {
            this.address = address;
            this.data = data;
            this.times = times;
        }

        public void run() {
            send(address, data);
            if (times < 3) {//最多发3次
                timer.schedule(new ResendTask(address,data,times+1), (int) (Math.pow(2, times+1))
                        * Client.DEFAULT_TIME_OUT);
            }
        }

        public byte[] getData() {
            return data;
        }
    }

    public static void main(String[] args) {
        new TFtpServer("e://").start();
    }

    /**
     * @return
     */
    public File getRoot() {
        return root;
    }

    /**
     * @return
     */
    public int getPort() {
        return port;
    }

    /**
     * @param i
     */
    public void setPort(int i) {
        port = i;
    }

}

TFtpPacketUtil.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * 创建日期 2004-8-30-12:49:20
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public final class TFtpPacketUtil {
  
  private TFtpPacketUtil() {
    
  }

  public static TFtpPacket decode(byte[] buf) throws BadPacketFormatException {
    if (buf==null || buf.length<4) {
      throw new BadPacketFormatException("packet too small");
    }
    int operateCode = buf[1];
    if (operateCode<TFtpPacket.RRQ || operateCode>TFtpPacket.ERROR) {
      throw new BadPacketFormatException("unknown operate code");
    }
    switch (operateCode) {
      case TFtpPacket.RRQ:
      case TFtpPacket.WRQ:
        return decodeRWPacket(buf);
      case TFtpPacket.DATA:
        return decodeDATAPacket(buf);
      case TFtpPacket.ACK:
        return decodeACKPacket(buf);
      case TFtpPacket.ERROR:
        return decodeERRORPacket(buf);
    }
    return null;
  }
  
  /**
   * 2 bytes       2 bytes string 1 byte
   * -----------------------------------------
   * | Opcode | ErrorCode | ErrMsg | 0 |
   * -----------------------------------------
   */
  private static TFtpPacket decodeERRORPacket(byte[] buf) throws BadPacketFormatException {
    if (buf.length<4) {
      throw new BadPacketFormatException("ack packet must >= 4 bytes");
    }
    ERRORPacket packet = new ERRORPacket();
    packet.setOperateCode(TFtpPacket.ERROR);
    packet.setErrorCode(buf[2]<<8+buf[3]);
    int end = 4;
    int i = 4;
    for (;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i!=buf.length) {
      String str = new String(buf,4,end-4);
      packet.setErrorMessage(str);
    }
    return packet;
  }


  /**
   * 2 bytes 2 bytes
   * ---------------------
   * | Opcode | Block # |
   * ---------------------
   * @param buf
   * @return
   */
  private static TFtpPacket decodeACKPacket(byte[] buf) throws BadPacketFormatException {
    displayBytes(buf);
    if (buf.length<4) {
      throw new BadPacketFormatException("ack packet must be 4 bytes");
    }
    ACKPacket packet = new ACKPacket();
    packet.setOperateCode(TFtpPacket.ACK);
    //System.out.println("buf[2]="+buf[2]+" buf[3]="+buf[3]+" total="+(buf[2]*256+buf[3]));
    packet.setBlock(byte2int(buf[2])*256+byte2int(buf[3]));
    //System.out.println("block:"+packet.getBlock());
    return packet;
  }


  /**
   * 2 bytes   2 bytes   n bytes
   * ----------------------------------
   * | Opcode | Block # | Data |
   * ----------------------------------
   * @param buf
   * @return
   */
  private static TFtpPacket decodeDATAPacket(byte[] buf) throws BadPacketFormatException  {
    if (buf.length<4) {
      throw new BadPacketFormatException("bad data packet");
    }
    DATAPacket packet = new DATAPacket();
    packet.setOperateCode(TFtpPacket.DATA);
    packet.setBlock(byte2int(buf[2])*256+byte2int(buf[3]));
    //System.out.println("decode data packet,block:"+packet.getBlock());
    byte[] data = new byte[buf.length-4];
    System.arraycopy(buf,4,data,0,data.length);
    packet.setData(data);
    return packet;
  }
  
  private static int byte2int(byte b) {
    if ((b&0x80)!=0) {
      return 128+(b&0x7f);
    }
    else {
      return b;
    }
  }


  /**
   * RRQ,WRQ packet format
   *  2 bytes    string   1 byte string 1 byte
   *  ------------------------------------------------
   *  | Opcode | Filename | 0 | Mode | 0 |
   *  ------------------------------------------------
   * @param buf
   * @return
   */
  private static TFtpPacket decodeRWPacket(byte[] buf) throws BadPacketFormatException {
    RWPacket packet = new RWPacket();
    packet.setOperateCode((int)buf[1]);
    int start = 2;
    int end = 2;
    int i;
    for (i=start;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i==buf.length) {
      throw new BadPacketFormatException();
    }
    packet.setFileName(new String(buf,start,end-start));
    start = end+1;
    end = start;
    for (i=start;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i==buf.length) {
      throw new BadPacketFormatException();
    }
    packet.setMode(new String(buf,start,end-start));
    return packet;
  }


  public static byte[] encode(TFtpPacket packet) {
    int operateCode = packet.getOperateCode();
    switch (operateCode) {
      case TFtpPacket.RRQ:
      case TFtpPacket.WRQ:
        return encodeRWPacket((RWPacket)packet);
      case TFtpPacket.DATA:
        return encodeDATAPacket((DATAPacket)packet);
      case TFtpPacket.ACK:
        return encodeACKPacket((ACKPacket)packet);
      case TFtpPacket.ERROR:
        return encodeERRORPacket((ERRORPacket)packet);
      
    }
    return null;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeERRORPacket(ERRORPacket packet) {
    byte[] messageBytes = null;
    if (packet.getErrorMessage()!=null) {
      messageBytes = packet.getErrorMessage().getBytes();
    }
    int size = messageBytes==null?0:messageBytes.length;
    size += 2+2+1;
    byte[] buf = new byte[size];
    buf[1] = (byte)(TFtpPacket.ERROR&0xff);
    int errorCode = packet.getErrorCode();
    buf[2] = (byte)((errorCode>>8)&0xff);
    buf[3] = (byte)(errorCode&0xff);
    if (messageBytes!=null) {
      System.arraycopy(messageBytes,0,buf,4,messageBytes.length);
    }
    return buf;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeACKPacket(ACKPacket packet) {
    byte[] buf = new byte[4];
    buf[1] = (byte)(TFtpPacket.ACK&0xff);
    int block = packet.getBlock();
    buf[2] = (byte)((block>>8)&0xff);
    buf[3] = (byte)(block&0xff);
    return buf;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeDATAPacket(DATAPacket packet) {
    byte[] data = packet.getData();
    int size = 2+2;
    if (data!=null) {
      size += data.length;
    }
    byte[] buf = new byte[size];
    System.out.println("encode data packet,buf[0]="+Integer.toHexString(buf[0]));
    buf[1] = (byte)(TFtpPacket.DATA&0xff);
    int block = packet.getBlock();
    buf[2] = (byte)((block>>8)&0xff);
    buf[3] = (byte)(block&0xff);
    if (data!=null) {
      System.arraycopy(data,0,buf,4,data.length);
    }
    return buf;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeRWPacket(RWPacket packet) {
    int operateCode = packet.getOperateCode();
    int size = 2;
    String fileName = packet.getFileName();
    String mode = packet.getMode();
    byte[] nameBytes = fileName.getBytes();//fileName must not null
    size += nameBytes.length+1;
    byte[] modeBytes = null;
    if (mode!=null) {
      modeBytes = mode.getBytes();
      size += modeBytes.length+1;
    }
    byte[] buf = new byte[size];
    buf[1] = (byte)(operateCode&0xff);
    System.arraycopy(nameBytes,0,buf,2,nameBytes.length);
    if (modeBytes!=null) {
      int pos = 2+nameBytes.length+1;
      System.arraycopy(modeBytes,0,buf,pos,modeBytes.length); 
    }
    return buf;
  }
  
  static int count = 0;
  
  public static void displayBytes(byte[] buf) {
    count++;
    if (buf==null) {
      System.out.println(count+":"+"null");
      return ;
    }
    StringBuffer sb = new StringBuffer();
    int len = buf.length>10?10:buf.length;
    for (int i=0;i<len;i++) {
      sb.append(Integer.toHexString(buf[i]));
    }
    System.out.println(count+":"+sb.toString());
  }
  
}

TFtpPacket.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 * 创建日期 2004-8-30-11:34:03
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public abstract class TFtpPacket {
  
  public static final int UNKNOWN = 0;  //unknown
  public static final int RRQ = 1;    //read request
  public static final int WRQ = 2;    //write request
  public static final int DATA = 3;  //data
  public static final int ACK = 4;    //Acknowledgment
  public static final int ERROR = 5;  //error
  
  private int operateCode = UNKNOWN;
  
  public int getOperateCode() {
    return operateCode;
  }

  /**
   * @param i
   */
  public void setOperateCode(int i) {
    operateCode = i;
  }

}

BadPacketFormatException.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * 创建日期 2004-8-30-11:54:24
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public class BadPacketFormatException extends Exception {
  
  public BadPacketFormatException() {
    super();
  }
  
  public BadPacketFormatException(String msg) {
    super(msg);
  }

}

RWPacket.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * 创建日期 2004-8-30-11:51:16
 *
 */
package starfire.tftp;


/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public class RWPacket extends TFtpPacket {

  private String fileName;
  private String mode;

  public RWPacket() {
    
  }

  /**
   * @return
   */
  public String getFileName() {
    return fileName;
  }

  /**
   * @return
   */
  public String getMode() {
    return mode;
  }

  /**
   * @param string
   */
  public void setFileName(String string) {
    fileName = string;
  }


  /**
   * @param string
   */
  public void setMode(String string) {
    mode = string;
  }
  
  public String toString() {
    return (getOperateCode()==TFtpPacket.RRQ?"read packet:":"write packet:")+"[fileName:="+
      fileName+"][mode="+mode+"]";
  }

}

ERRORPacket.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * 创建日期 2004-8-30-13:07:55
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public class ERRORPacket extends TFtpPacket {
  
  /**
   * 错误码
   * Value Meaning
   * 0 未定义,请参阅错误信息(如果提示这种信息的话)
   * 1 文件未找到
   * 2 访问非法
   * 3 磁盘满或超过分配的配额
   * 4 非法的TFTP操作
   * 5 未知的传输ID
   * 6 文件已经存在
   * 7 没有类似的用户
   */
  public static final int NOT_DEFINED_CODE = 0;
  public static final int FILE_NOT_FOUND_CODE = 1;
  public static final int ILLEGAL_ACCESS_CODE = 2;
  public static final int DISK_FULL_CODE = 3;
  public static final int ILLEGAL_OPERATE_CODE = 4;
  public static final int UNKNOWN_ID_CODE = 5;
  public static final int FILE_EXIST_CODE = 6;
  public static final int USER_NOT_EXIST_CODE = 7;
  
  
  private int errorCode;
  private String errorMessage;
  
  public ERRORPacket() {
    setOperateCode(TFtpPacket.ERROR);
  }

  /**
   * @return
   */
  public int getErrorCode() {
    return errorCode;
  }

  /**
   * @return
   */
  public String getErrorMessage() {
    return errorMessage;
  }

  /**
   * @param i
   */
  public void setErrorCode(int i) {
    errorCode = i;
  }

  /**
   * @param string
   */
  public void setErrorMessage(String string) {
    errorMessage = string;
  }

  public String toString() {
    return "Error packet:[errorCode="+errorCode+"][errorMessage="+errorMessage+"]";
  }
}

DATAPacket.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
 * 创建日期 2004-8-30-13:04:07
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public class DATAPacket extends TFtpPacket {
  private int block;
  private byte[] data;
  
  public DATAPacket() {
    setOperateCode(TFtpPacket.DATA);
  }

  /**
   * @return
   */
  public int getBlock() {
    return block;
  }

  /**
   * @return
   */
  public byte[] getData() {
    return data;
  }

  /**
   * @param block
   */
  public void setBlock(int block) {
    this.block = block;
  }

  /**
   * @param data
   */
  public void setData(byte[] data) {
    this.data = data;
  }

  public String toString() {
    return "Data packet:[block="+block+"][data size="+(data==null?0:data.length)+"]";
  }
}

ACKPacket.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
 * 创建日期 2004-8-30-13:05:47
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public class ACKPacket extends TFtpPacket {
  private int block;
  
  public ACKPacket() {
    setOperateCode(TFtpPacket.ACK);
  }
  
  /**
   * @return
   */
  public int getBlock() {
    return block;
  }

  /**
   * @param i
   */
  public void setBlock(int i) {
    block = i;
  }
  
  public String toString() {
    return "Ack packet:[block="+block+"]";
  }

}
### 配置和使用TFTP服务器 TFTP(Trivial File Transfer Protocol)是一种用于在网络中进行简单文件传输的协议。它通常基于UDP协议实现,端口号为69。由于其设计简单、开销小,TFTP广泛应用于嵌入式系统和无盘设备中,用于快速传输配置文件或固件。 #### 1. 安装TFTP服务器 在Ubuntu系统中,可以通过安装`**tftpd-hpa**`和`**tftp-hpa**`软件包来搭建TFTP服务器。具体命令如下: ```bash sudo apt-get install tftp-hpa tftpd-hpa ``` 此命令将安装TFTP服务器和客户端所需的组件,确保服务器能够正常运行并响应客户端请求。 #### 2. 配置TFTP服务器目录 TFTP服务器需要一个特定的目录来存储传输的文件。通常,这个目录被设置为`**/home/用户名/tftpboot**`。创建目录并设置权限的命令如下: ```bash mkdir /home/wht/linux/tftpboot chmod 777 /home/wht/linux/tftpboot ``` 上述命令创建了一个名为`tftpboot`的目录,并赋予所有用户读、写、执行的权限,以确保TFTP服务器能够正常访问该目录。 #### 3. 修改TFTP服务器配置文件 在Ubuntu中,TFTP服务器的配置文件通常位于`**/etc/default/tftpd-hpa**`。可以通过编辑该文件来调整服务器的配置。例如: ```bash sudo nano /etc/default/tftpd-hpa ``` 在配置文件中,可以设置以下参数: - `**TFTP_USERNAME**`: 指定运行TFTP服务的用户。 - `**TFTP_DIRECTORY**`: 指定TFTP服务器的根目录,例如`**/home/wht/linux/tftpboot**`。 - `**TFTP_ADDRESS**`: 指定服务器的IP地址和端口,例如`**:69**`。 - `**TFTP_OPTIONS**`: 可选参数,例如`**--secure**`或`**--create**`,用于增强安全性或允许客户端上传文件。 #### 4. 重启TFTP服务 完成配置后,需要重启TFTP服务以使更改生效。使用以下命令重启服务: ```bash sudo systemctl restart tftpd-hpa ``` #### 5. 使用TFTP客户端传输文件 在客户端,可以使用`**tftp**`命令连接到TFTP服务器并传输文件。以下是一些常用的命令示例: - **下载文件**: ```bash tftp 192.168.1.100 tftp> get filename.txt ``` - **上传文件**: ```bash tftp 192.168.1.100 tftp> put filename.txt ``` 在上述命令中,`**192.168.1.100**`是TFTP服务器的IP地址,`**filename.txt**`是要传输的文件名。 #### 6. TFTP命令参数说明 - `**-l**`: 指定本地文件名,通常用于上传或下载时重命名文件。 - `**-r**`: 指定远程文件名,即服务器上的文件名。 - `**-g**`: 下载文件时使用。 - `**-p**`: 上传文件时使用。 #### 7. 验证TFTP服务器状态 可以通过以下命令检查TFTP服务的状态: ```bash sudo systemctl status tftpd-hpa ``` 如果服务运行正常,将显示“active (running)”状态。 #### 8. 防火墙设置 确保服务器的防火墙允许UDP端口69通过,以支持TFTP通信。可以使用以下命令开放端口: ```bash sudo ufw allow 69/udp ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值