Android API-23: InetAddressUtils replacement

后端 未结 5 1960
误落风尘
误落风尘 2020-12-30 01:07

Switching to Android Marshmallow API, I was using org.apache.http.conn.util.InetAddressUtils for InetAddressUtils.isIPv4Address(ipAddress) in a cod

5条回答
  •  隐瞒了意图╮
    2020-12-30 01:27

    I couldn't find something better than converting to Inet4Address or Inet6Address

    public boolean isValidIp4Address(final String hostName) {
          try {
             return Inet4Address.getByName(hostName) != null;
         } catch (UnknownHostException ex) {
             return false;
         } 
    }
    
    public boolean isValidIp6Address(final String hostName) {
          try {
             return Inet6Address.getByName(hostName) != null;
         } catch (UnknownHostException ex) {
             return false;
         } 
    }
    

    Note, the getHostByName actually does the lookup, which isn't always desirable.

    Or, you can get source of InetAddessUtils, which unlike getByName(), doesn't do the lookup, but accepts only dotted addresses. The code is really tiny. It uses regexp classes which are supported by Android. Just remove Immutable annotation which isn't really important, and it will compile!

提交回复
热议问题