2 * Copyright (c) 2010-2024 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.mercedesme.internal.server;
15 import java.net.Inet4Address;
16 import java.net.InetAddress;
17 import java.net.NetworkInterface;
18 import java.net.SocketException;
19 import java.util.ArrayList;
20 import java.util.Enumeration;
21 import java.util.List;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.mercedesme.internal.Constants;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * The {@link Utils} class defines an HTTP Server for authentication callbacks
31 * @author Bernd Weymann - Initial contribution
35 private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
36 private static final List<Integer> PORTS = new ArrayList<>();
37 private static int port = 8090;
40 * Get free port without other Thread interference
44 public static synchronized int getFreePort() {
45 while (PORTS.contains(port)) {
52 public static synchronized void addPort(int portNr) {
53 if (PORTS.contains(portNr)) {
54 LOGGER.warn("Port {} already occupied", portNr);
59 public static synchronized void removePort(int portNr) {
60 PORTS.remove(Integer.valueOf(portNr));
63 public static String getCallbackIP() throws SocketException {
64 // https://stackoverflow.com/questions/901755/how-to-get-the-ip-of-the-computer-on-linux-through-java
65 // https://stackoverflow.com/questions/1062041/ip-address-not-obtained-in-java
66 for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
67 .hasMoreElements();) {
68 NetworkInterface iface = ifaces.nextElement();
70 if (!iface.isLoopback()) {
72 for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses
73 .hasMoreElements();) {
74 InetAddress address = addresses.nextElement();
75 if (address instanceof Inet4Address) {
76 return address.getHostAddress();
81 } catch (SocketException se) {
82 // Calling one network interface failed - continue searching
83 LOGGER.trace("Network {} failed {}", iface.getName(), se.getMessage());
86 throw new SocketException("IP address not detected");
89 public static String getCallbackAddress(String callbackIP, int callbackPort) {
90 return "http://" + callbackIP + Constants.COLON + callbackPort + Constants.CALLBACK_ENDPOINT;