tryParse static method

DVPeerAddress? tryParse(
  1. String text
)

Reads 1.2.3.4, 1.2.3.4:80, 2001:db8::1, [2001:db8::1] and [2001:db8::1]:80. A zone on an IPv6 address ([fe80::1%2]:80) is dropped: it names an interface on this host, not a different peer.

Implementation

static DVPeerAddress? tryParse(String text) {
  if (text.isEmpty || text.length > 64) return null;
  String host;
  String? port;
  if (text.startsWith('[')) {
    final int close = text.indexOf(']');
    if (close < 0) return null;
    host = text.substring(1, close);
    final String rest = text.substring(close + 1);
    if (rest.isNotEmpty) {
      if (!rest.startsWith(':')) return null;
      port = rest.substring(1);
    }
  } else {
    final int first = text.indexOf(':');
    if (first >= 0 && first == text.lastIndexOf(':')) {
      // One colon: IPv4 with a port. Two or more is a bare IPv6 address.
      host = text.substring(0, first);
      port = text.substring(first + 1);
    } else {
      host = text;
    }
  }
  final int zone = host.indexOf('%');
  if (zone >= 0 && host.contains(':')) host = host.substring(0, zone);
  final DVIpAddress? address = DVIpAddress.tryParse(host);
  if (address == null) return null;
  if (port == null) return DVPeerAddress(address);
  if (port.isEmpty ||
      port.length > 5 ||
      port.codeUnits.any((int u) => u < 0x30 || u > 0x39)) {
    return null;
  }
  final int value = int.parse(port);
  if (value > 65535) return null;
  return DVPeerAddress(address, port: value);
}