2 * Copyright (c) 2010-2022 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.InetAddress;
16 import java.net.NetworkInterface;
17 import java.net.SocketException;
18 import java.util.ArrayList;
19 import java.util.Enumeration;
20 import java.util.List;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.openhab.binding.mercedesme.internal.Constants;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 * The {@link Utils} class defines an HTTP Server for authentication callbacks
30 * @author Bernd Weymann - Initial contribution
34 private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
35 private static final List<Integer> PORTS = new ArrayList<Integer>();
36 private static int port = 8090;
39 * Get free port without other Thread interference
43 public static synchronized int getFreePort() {
44 while (PORTS.contains(port)) {
51 public static synchronized void addPort(int portNr) {
52 if (PORTS.contains(portNr)) {
53 LOGGER.warn("Port {} already occupied", portNr);
58 public static synchronized void removePort(int portNr) {
59 PORTS.remove(Integer.valueOf(portNr));
62 public static String getCallbackIP() throws SocketException {
63 // https://stackoverflow.com/questions/1062041/ip-address-not-obtained-in-java
64 for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
65 .hasMoreElements();) {
66 NetworkInterface iface = ifaces.nextElement();
68 if (!iface.isLoopback()) {
70 for (Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses
71 .hasMoreElements();) {
72 InetAddress address = addresses.nextElement();
73 return address.getHostAddress();
77 } catch (SocketException se) {
78 // Calling one network interface failed - continue searching
79 LOGGER.trace("Network {} failed {}", iface.getName(), se.getMessage());
82 throw new SocketException("IP address not detected");
85 public static String getCallbackAddress(String callbackIP, int callbackPort) {
86 return "http://" + callbackIP + Constants.COLON + callbackPort + Constants.CALLBACK_ENDPOINT;