1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-06-17 08:54:49 +02:00
Smack/smack-core/src/test/java/org/jivesoftware/smack/util/NetworkUtil.java
Florian Schmaus 9352225f44 Rework SOCKS5 unit tests so that they can be run in parallel
As result it is now also possible to start multiple local SOCKS5
proxies with different port, which is usually not necessary in real
life but useful for unit tests.
2019-06-02 10:38:19 +02:00

54 lines
1.8 KiB
Java

/**
*
* Copyright 2016-2019 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.util;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetworkUtil {
private static final Logger LOGGER = Logger.getLogger(NetworkUtil.class.getName());
public static ServerSocket getSocketOnLoopback() throws IOException {
final InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
final int portMin = 1024;
final int portMax = (1 << 16) - 1;
final int backlog = 1;
ServerSocket serverSocket = null;
for (int port = portMin; port <= portMax; port++) {
try {
serverSocket = new ServerSocket(port, backlog, loopbackAddress);
break;
} catch (BindException e) {
LOGGER.log(Level.FINEST, "Could not bind port " + port + ", trying next", e);
}
}
if (serverSocket == null) {
throw new IOException("Could not bind any port between " + portMin + " and " + portMax
+ " on loopback address" + loopbackAddress);
}
return serverSocket;
}
}