001    /*--------------------------------------------------------------------------+
002    $Id: SocketUtils.java 28668 2010-06-23 14:46:45Z heineman $
003    |                                                                          |
004    | Copyright 2005-2010 Technische Universitaet Muenchen                     |
005    |                                                                          |
006    | Licensed under the Apache License, Version 2.0 (the "License");          |
007    | you may not use this file except in compliance with the License.         |
008    | You may obtain a copy of the License at                                  |
009    |                                                                          |
010    |    http://www.apache.org/licenses/LICENSE-2.0                            |
011    |                                                                          |
012    | Unless required by applicable law or agreed to in writing, software      |
013    | distributed under the License is distributed on an "AS IS" BASIS,        |
014    | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
015    | See the License for the specific language governing permissions and      |
016    | limitations under the License.                                           |
017    +--------------------------------------------------------------------------*/
018    package edu.tum.cs.commons.net;
019    
020    import java.io.IOException;
021    import java.net.ServerSocket;
022    
023    /**
024     * Utility methods used in conjunction with sockets.
025     * 
026     * @author hummelb
027     * @author $Author: heineman $
028     * @version $Rev: 28668 $
029     * @levd.rating GREEN Hash: 66E2820DADBD6636110BD951A76A091E
030     */
031    public class SocketUtils {
032    
033            /** Checks whether the given TCP port is available. */
034            public static boolean isFreePort(int portNumber) {
035                    try {
036                            ServerSocket socket = new ServerSocket(portNumber);
037                            socket.setReuseAddress(true);
038                            socket.close();
039                            return true;
040                    } catch (IOException e) {
041                            return false;
042                    }
043            }
044    
045            /** Returns a new free TCP port number */
046            public static int getFreePort() throws IOException {
047                    ServerSocket socket = new ServerSocket(0);
048                    socket.setReuseAddress(true);
049                    int result = socket.getLocalPort();
050                    socket.close();
051                    return result;
052            }
053    
054    }