1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.net.dhcp;
18 
19 import java.net.Inet4Address;
20 import java.nio.ByteBuffer;
21 
22 /**
23  * This class implements the DHCP-NAK packet.
24  */
25 public class DhcpNakPacket extends DhcpPacket {
26     /**
27      * Generates a NAK packet with the specified parameters.
28      */
DhcpNakPacket(int transId, short secs, Inet4Address relayIp, byte[] clientMac, boolean broadcast)29     DhcpNakPacket(int transId, short secs, Inet4Address relayIp, byte[] clientMac,
30             boolean broadcast) {
31         super(transId, secs, INADDR_ANY /* clientIp */, INADDR_ANY /* yourIp */,
32                 INADDR_ANY /* nextIp */, relayIp, clientMac, broadcast);
33     }
34 
toString()35     public String toString() {
36         String s = super.toString();
37         return s + " NAK, reason " + (mMessage == null ? "(none)" : mMessage);
38     }
39 
40     /**
41      * Fills in a packet with the requested NAK attributes.
42      */
buildPacket(int encap, short destUdp, short srcUdp)43     public ByteBuffer buildPacket(int encap, short destUdp, short srcUdp) {
44         ByteBuffer result = ByteBuffer.allocate(MAX_LENGTH);
45         // Constructor does not set values for layers <= 3: use empty values
46         Inet4Address destIp = INADDR_ANY;
47         Inet4Address srcIp = INADDR_ANY;
48 
49         fillInPacket(encap, destIp, srcIp, destUdp, srcUdp, result, DHCP_BOOTREPLY, mBroadcast);
50         result.flip();
51         return result;
52     }
53 
54     /**
55      * Adds the optional parameters to the client-generated NAK packet.
56      */
finishPacket(ByteBuffer buffer)57     void finishPacket(ByteBuffer buffer) {
58         addTlv(buffer, DHCP_MESSAGE_TYPE, DHCP_MESSAGE_TYPE_NAK);
59         addTlv(buffer, DHCP_SERVER_IDENTIFIER, mServerIdentifier);
60         addTlv(buffer, DHCP_MESSAGE, mMessage);
61         addTlvEnd(buffer);
62     }
63 }
64