DHCP(Dynamic Host Configuration Protocol),动态主机配置协议,是一个应用层协议。当我们将客户主机IP地址设置为动态获取方式时,DHCP服务器就会根据DHCP协议给客户端分配IP,使得客户端机器能够利用这个IP上网。我们的电脑和手机使用WIFI的时候,都是使用DHCP协议来获取IP的。
ipconfig /all
windows系统下,我们可以使用上面的命令查看IP的获取方式和DHCP服务器地址。
更多工作原理相关,查看DHCP百度百科。
maven依赖
<dependency> <groupId>com.helger</groupId> <artifactId>dhcp4java</artifactId> <version>1.1.0</version> </dependency>
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import org.dhcp4java.DHCPConstants; import org.dhcp4java.DHCPPacket; import org.dhcp4java.HardwareAddress; public class DHCPTest { public static void main(String[] args) throws IOException { //当前电脑的物理地址 byte[] macAddress = HardwareAddress.getHardwareAddressByString("5C:80:B6:FD:91:A7") .getHardwareAddress(); //封装DHCP请求包 DHCPPacket discover = new DHCPPacket(); //发送DISCOVER报文 discover.setOp(DHCPConstants.DHCPDISCOVER); //硬件类别为以太网 discover.setHtype(DHCPConstants.HTYPE_ETHER); //硬件地址长度 以太网为6 discover.setHlen((byte) 6); //局域网为0 discover.setHops((byte) 0); //请求ID discover.setXid(123); //客户端启动时间(秒) discover.setSecs((short) 10000); discover.setFlags((short) 0); //客户端的硬件地址 discover.setChaddr(macAddress); //消息类型 discover.setDHCPMessageType(DHCPConstants.DHCPDISCOVER); //客户端请求服务器的68端口,服务器请求客户端的67端口 DatagramSocket socket = new DatagramSocket(DHCPConstants.BOOTP_REPLY_PORT); byte[] discoverBytes = discover.serialize(); DatagramPacket sendPacket = new DatagramPacket(discoverBytes, discoverBytes.length, InetAddress.getByName("255.255.255.255"), DHCPConstants.BOOTP_REQUEST_PORT); //发送请求报文 socket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(new byte[1500], 1500); //接收服务器的响应报文 socket.receive(receivePacket); DHCPPacket resultDhcpPacket = DHCPPacket.getPacket(receivePacket); //返回报文包含macAddress if (bytesToHexString(resultDhcpPacket.getChaddr()).contains( bytesToHexString(macAddress))) { //获取的IP地址 System.out.println(resultDhcpPacket.getYiaddr());//192.168.0.142 } socket.close(); } private static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(); for (byte b : src) { int v = b & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } }
查看当前电脑的物理地址,5C:80:B6:FD:91:A7
DHCP百度百科
java实现DHCP协议获取ip地址
java 探测网络中是否有dhcp环境
Wireshark分析DHCP