Advertisement
Guest User

Untitled

a guest
Oct 30th, 2014
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. private boolean isPortInUse(String hostName, int portNumber) {
  2. boolean result;
  3.  
  4. try {
  5.  
  6. Socket s = new Socket(hostName, portNumber);
  7. s.close();
  8. result = true;
  9.  
  10. }
  11. catch(Exception e) {
  12. result = false;
  13. }
  14.  
  15. return(result);
  16. }
  17.  
  18. private boolean isPortInUse(String host, int port) {
  19. // Assume no connection is possible.
  20. boolean result = false;
  21.  
  22. try {
  23. (new Socket(host, port)).close();
  24. result = true;
  25. }
  26. catch(SocketException e) {
  27. // Could not connect.
  28. }
  29.  
  30. return result;
  31. }
  32.  
  33. private boolean availablePort(String host, int port) {
  34. // Assume port is available.
  35. boolean result = true;
  36.  
  37. try {
  38. (new Socket(host, port)).close();
  39.  
  40. // Successful connection means the port is taken.
  41. result = false;
  42. }
  43. catch(SocketException e) {
  44. // Could not connect.
  45. }
  46.  
  47. return result;
  48. }
  49.  
  50. public SocketAnalyzer extends java.net.Socket {
  51. public boolean isPortAvailable() {
  52. // ... code here ...
  53. }
  54. }
  55.  
  56. private boolean availablePort(String host, int port) {
  57. return (new SocketAnalyzer(host, port)).isPortAvailable();
  58. }
  59.  
  60. if( (new SocketAnalyzer(host, port)).isPortAvailable() ) {
  61. // Launch the server socket on 'port'!
  62. }
  63.  
  64. // The constructor would have to bind to the host/port combination...
  65. // This is arguably poor form as the constructor really shouldn't do anything.
  66. // You could, instead, use the superclass' constructor and then call bind,
  67. // but for the purposes of this example, the idea is key: inherit.
  68. ServerSocketAnalyzer ssa = new ServerSocketAnalyzer( host, port );
  69.  
  70. if( ssa.isPortAvailable() ) {
  71. // Code to use the server socket...
  72. Socket s = ssa.accept();
  73. }
  74.  
  75. private boolean isPortInUse(int port) {
  76. try {
  77. // ServerSocket try to open a LOCAL port
  78. new ServerSocket(port).close();
  79. // port can be opened, it's available
  80. return false;
  81. } catch(IOException e) {
  82. // port cannot be opened, it's in use
  83. return true;
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement