DHCPPacket is the central class allowing manipulation of DHCP packets. A generic framework for DHCP servers is also availaible, on a development model similar to HTTP Servlets.
It is centered around the 3 following classes:
DHCPPacket packet data manipulation
DHCPConstants commonly used DHCP constants (better used through static imports) import static sf.dhcp4java.DHCPConstants.*;tt>
DHCPOption DHCP option manipulation, it is used internally since DHCPPacket provides helper functions. It is however useful if you want to create options lists and set them at once instead of one by one.
There are two basic ways to build a new DHCPPacket object.
First one is to build an object from scratch using the constructor and setters.
DHCPPacket discover = new DHCPPacket(); discover.setOp(DHCPPacket.BOOTREQUEST); discover.setHtype(DHCPPacket.HTYPE_ETHER); discover.setHlen((byte) 6); discover.setHops((byte) 0); discover.setXid( (new Random()).nextInt() ); ...Second is to decode a DHCP datagram received from the network. (simple DHCP sniffer). In this case, the object is created through a singleton factory
DatagramSocket socket = new DatagramSocket(67); while (true) { DatagramPacket pac = new DatagramPacket(new byte[1500], 1500); socket.receive(pac); DHCPPacket dhcp = DHCPPacket.getPacket(pac); System.out.println(dhcp.toString()); }
Note: this package does not contain a full blown DHCP server but only a framework with simple examples.
This framework is very close to the HTTP Servlet framework.
The service() method is systematically called, and dispatches control to more specific methods as its default behaviour.
doDiscover(), doRequest(), doInform(), doDecline(), doRelease()
Note: only valid DHCP datagrams are passed to servlets. Invalid packets are discarded. However, you can override DatagramPacket serviceDatagram(DatagramPacket) if you want a chance to treat every datagram received even malformed.
Configuration: the Server reads the following properties in "/DHCPd.properties" at the root of the class path. You can however provide a properties set when contructing the server. Default values are:
serverAddress=127.0.0.1:67 [address:port]
serverThreads=2 [number of concurrent threads for servlets]
Standard way of running the Server:
public static void main(String[] args) { try { DHCPServer server = DHCPServer.initServer(new TrivialDHCPServlet(), null); new Thread(server).start(); } catch (ServerInitException e) { // die gracefully } }