2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.network.internal.dhcp;
15 import java.net.SocketException;
17 import java.util.TreeMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * A singleton. IPRequestReceivedCallback objects can register and unregister.
26 * If the first one is registered and there is no singleton instance, an instance will be created and the
27 * receiver thread will be started. If the last IPRequestReceivedCallback is removed, the thread will be stopped
28 * after the receive socket is closed.
29 * IPRequestReceivedCallback will be called for the address that is registered and matches the
30 * DHO_DHCP_REQUESTED_ADDRESS address field.
32 * @author David Graeff - Initial contribution
35 public class DHCPListenService {
36 static @Nullable DHCPPacketListenerServer instance;
37 private static Map<String, IPRequestReceivedCallback> registeredListeners = new TreeMap<>();
38 private static Logger logger = LoggerFactory.getLogger(DHCPListenService.class);
40 public static synchronized DHCPPacketListenerServer register(String hostAddress,
41 IPRequestReceivedCallback dhcpListener) throws SocketException {
42 DHCPPacketListenerServer instance = DHCPListenService.instance;
43 if (instance == null) {
44 instance = new DHCPPacketListenerServer((String ipAddress) -> {
45 IPRequestReceivedCallback listener = registeredListeners.get(ipAddress);
46 if (listener != null) {
47 listener.dhcpRequestReceived(ipAddress);
49 logger.trace("DHCP request for unknown address: {}", ipAddress);
52 DHCPListenService.instance = instance;
55 synchronized (registeredListeners) {
56 registeredListeners.put(hostAddress, dhcpListener);
61 public static void unregister(String hostAddress) {
62 synchronized (registeredListeners) {
63 registeredListeners.remove(hostAddress);
64 if (!registeredListeners.isEmpty()) {
69 final DHCPPacketListenerServer instance = DHCPListenService.instance;
70 if (instance != null) {
73 DHCPListenService.instance = null;