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-DISCOVER packet.
24  */
25 public class DhcpDiscoverPacket extends DhcpPacket {
26     /**
27      * The IP address of the client which sent this packet.
28      */
29     final Inet4Address mSrcIp;
30 
31     /**
32      * Generates a DISCOVER packet with the specified parameters.
33      */
DhcpDiscoverPacket(int transId, short secs, Inet4Address relayIp, byte[] clientMac, boolean broadcast, Inet4Address srcIp, boolean rapidCommit)34     DhcpDiscoverPacket(int transId, short secs, Inet4Address relayIp, byte[] clientMac,
35             boolean broadcast, Inet4Address srcIp, boolean rapidCommit) {
36         super(transId, secs, INADDR_ANY, INADDR_ANY, INADDR_ANY, relayIp, clientMac, broadcast);
37         mSrcIp = srcIp;
38         mRapidCommit = rapidCommit;
39     }
40 
toString()41     public String toString() {
42         String s = super.toString();
43         return s + " DISCOVER " +
44                 (mBroadcast ? "broadcast " : "unicast ");
45     }
46 
47     /**
48      * Fills in a packet with the requested DISCOVER parameters.
49      */
buildPacket(int encap, short destUdp, short srcUdp)50     public ByteBuffer buildPacket(int encap, short destUdp, short srcUdp) {
51         ByteBuffer result = ByteBuffer.allocate(MAX_LENGTH);
52         fillInPacket(encap, INADDR_BROADCAST, mSrcIp, destUdp, srcUdp, result, DHCP_BOOTREQUEST,
53                 mBroadcast);
54         result.flip();
55         return result;
56     }
57 
58     /**
59      * Adds optional parameters to a DISCOVER packet.
60      */
finishPacket(ByteBuffer buffer)61     void finishPacket(ByteBuffer buffer) {
62         addTlv(buffer, DHCP_MESSAGE_TYPE, DHCP_MESSAGE_TYPE_DISCOVER);
63         addTlv(buffer, DHCP_CLIENT_IDENTIFIER, getClientId());
64         addCommonClientTlvs(buffer);
65         addTlv(buffer, DHCP_PARAMETER_LIST, mRequestedParams);
66         if (mRapidCommit) {
67             addTlv(buffer, DHCP_RAPID_COMMIT);
68         }
69         addTlvEnd(buffer);
70     }
71 }
72