]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.application/src/org/simantics/application/db/SocketUtils.java
331b5efc0294a955d49b2990b5fdf9aab2363e61
[simantics/platform.git] / bundles / org.simantics.application / src / org / simantics / application / db / SocketUtils.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.application.db;\r
13 \r
14 import java.net.BindException;\r
15 import java.net.Socket;\r
16 \r
17 /**\r
18  * @author Tuukka Lehtonen\r
19  */\r
20 public class SocketUtils {\r
21 \r
22     /**\r
23      * @return free ephemeral port for a TCP socket\r
24      */\r
25     public static int getFreeEphemeralPort() {\r
26         while (true) {\r
27             try {\r
28                 Socket s = null;\r
29                 try {\r
30                     s = new Socket();\r
31                     s.bind(null);\r
32                     return s.getLocalPort();\r
33                 } finally {\r
34                     if (s != null)\r
35                         s.close();\r
36                 }\r
37             } catch (BindException e) {\r
38                 // Nothing to do, try next port\r
39             } catch (Throwable e) {\r
40                 throw new Error(e);\r
41             }\r
42         }\r
43     }\r
44 \r
45 }\r