Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private boolean isPortInUse(String hostName, int portNumber) {
- boolean result;
- try {
- Socket s = new Socket(hostName, portNumber);
- s.close();
- result = true;
- }
- catch(Exception e) {
- result = false;
- }
- return(result);
- }
- private boolean isPortInUse(String host, int port) {
- // Assume no connection is possible.
- boolean result = false;
- try {
- (new Socket(host, port)).close();
- result = true;
- }
- catch(SocketException e) {
- // Could not connect.
- }
- return result;
- }
- private boolean availablePort(String host, int port) {
- // Assume port is available.
- boolean result = true;
- try {
- (new Socket(host, port)).close();
- // Successful connection means the port is taken.
- result = false;
- }
- catch(SocketException e) {
- // Could not connect.
- }
- return result;
- }
- public SocketAnalyzer extends java.net.Socket {
- public boolean isPortAvailable() {
- // ... code here ...
- }
- }
- private boolean availablePort(String host, int port) {
- return (new SocketAnalyzer(host, port)).isPortAvailable();
- }
- if( (new SocketAnalyzer(host, port)).isPortAvailable() ) {
- // Launch the server socket on 'port'!
- }
- // The constructor would have to bind to the host/port combination...
- // This is arguably poor form as the constructor really shouldn't do anything.
- // You could, instead, use the superclass' constructor and then call bind,
- // but for the purposes of this example, the idea is key: inherit.
- ServerSocketAnalyzer ssa = new ServerSocketAnalyzer( host, port );
- if( ssa.isPortAvailable() ) {
- // Code to use the server socket...
- Socket s = ssa.accept();
- }
- private boolean isPortInUse(int port) {
- try {
- // ServerSocket try to open a LOCAL port
- new ServerSocket(port).close();
- // port can be opened, it's available
- return false;
- } catch(IOException e) {
- // port cannot be opened, it's in use
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement