Android How to - Get port and Host from IP address








Question

We would like to know how to get port and Host from IP address.

Answer

class IPAddress {
/*  w w  w . j a v  a  2s  .  co  m*/
  static public int getPort(String address) {
    int index = address.indexOf(':');
    if (index != -1) {
      try {
        return Integer.parseInt(address.substring(index + 1, address.length()));
      } catch (Exception ex) {
      }
    }
    return -1;
  }

  static public String getHost(String address) {
    int index = address.indexOf(':');
    if (index != -1) {
      return address.substring(0, index);
    }
    return address;
  }

}