getIpAddress function

Future<String?> getIpAddress()

Get full Ipv6 or Ipv4 address:

  • 192.168.000.001
  • fe80:0000:0000:0820:a918:0000:0000:74b3

Implementation

Future<String?> getIpAddress() async {
  for (final InternetAddress internetAddress in (await NetworkInterface.list(
    includeLinkLocal: true,
    includeLoopback: true,
  ))
      .fold<List<InternetAddress>>(
    <InternetAddress>[],
    (List<InternetAddress> previousValue, NetworkInterface element) {
      if (Platform.isIOS && !element.name.contains('en')) {
        return previousValue;
      }
      if (Platform.isAndroid && !element.name.contains('wlan')) {
        return previousValue;
      }
      return previousValue..addAll(element.addresses);
    },
  )) {
    if (!internetAddress.isLoopback) {
      if (internetAddress.type == InternetAddressType.IPv6) {
        return internetAddress.address.formatExpandedIpv6Address();
      }

      if (internetAddress.type == InternetAddressType.IPv4) {
        return internetAddress.address.formatExpandedIpv4Address();
      }

      return internetAddress.address;
    }
  }

  return null;
}