6

I am trying to connect to a my remote server from my Android device. How do I check if a specific port on my server is open? Eg. how to check if port 80 is open on my server 11.11.11.11?

Currently, I am using InetAddress to ping if the host is reachable but this does not tell me if the port 80 is open.

Current Code

boolean isAvailable = false;
try {
    isAvailable = InetAddress.getByName("11.11.11.11").isReachable(2000);
    if (isAvailable == true) {
       //host is reachable
       doSomething();
    }
} catch (Exception e) {

}
Emil Ivanov
  • 36,548
  • 11
  • 71
  • 90
newbie
  • 948
  • 4
  • 12
  • 25
  • I think your app should not care for that. Just display "connection to server died" message if you catch exception thrown because of connection problems. – hovanessyan Nov 12 '11 at 15:40
  • yup, the problem is the app hangs when it is taking too long to try to connect. I have mitigated the problem by using a loading screen while it is testing the connection to server. Still not the ideal solution though – newbie Nov 18 '11 at 18:30

2 Answers2

9

Create a Socket that will check that the given ip with particular port could be connected or not.

public static boolean isPortOpen(final String ip, final int port, final int timeout) {

    try {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), timeout);
        socket.close();
        return true;
    } 

    catch(ConnectException ce){
        ce.printStackTrace();
        return false;
    }

    catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}     
Ken Ratanachai S.
  • 2,927
  • 31
  • 40
Himanshu Joshi
  • 3,351
  • 1
  • 18
  • 31
  • I tried to do that ... but each time the code executed, i got error message, "Connection Refused" what's that mean @Morpheus...? Actually this is happened when Two Devices are already connected in between AP and Client. – gumuruh Aug 09 '14 at 04:08
1

Runtime.getRuntime().exec() and pass command to it to get various port entry with pid. Commands are below:

“cat /proc/net/tcp”, “cat /proc/net/tcp6”, “cat /proc/net/udp”, “cat /proc/net/udp6”.

Here is explanation with source code. I have tested it. :

http://kickwe.com/tutorial/android-port-scanner-tutorial/

amigo
  • 21
  • 4