Line data Source code
1 : import 'package:universal_io/io.dart';
2 :
3 : /// Represents a network interface with its network ID, host ID, and IP address.
4 : class NetInterface {
5 : /// Creates a [NetInterface] with the given [networkId], [hostId], and [ipAddress].
6 1 : NetInterface({
7 : required this.networkId,
8 : required this.hostId,
9 : required this.ipAddress,
10 : });
11 :
12 : final String networkId;
13 : final int hostId;
14 : final String ipAddress;
15 :
16 : /// Returns the local network interface information for the first available IPv4 interface.
17 : ///
18 : /// This method fetches the list of network interfaces and returns a [NetInterface]
19 : /// object for the first interface found, or null if none are available.
20 1 : static Future<NetInterface?> localInterface() async {
21 1 : final interfaceList = await NetworkInterface.list(
22 : type: InternetAddressType.IPv4,
23 : ); //will give interface list
24 1 : if (interfaceList.isNotEmpty) {
25 : final localInterface =
26 1 : interfaceList.first; //fetching first interface like en0/eth0
27 2 : if (localInterface.addresses.isNotEmpty) {
28 1 : final address = localInterface.addresses
29 1 : .elementAt(0)
30 1 : .address; //gives IP address of GHA local machine.
31 2 : final networkId = address.substring(0, address.lastIndexOf('.'));
32 1 : final hostId = int.parse(
33 4 : address.substring(address.lastIndexOf('.') + 1, address.length),
34 : );
35 1 : return NetInterface(
36 : networkId: networkId,
37 : hostId: hostId,
38 : ipAddress: address,
39 : );
40 : }
41 : }
42 : return null;
43 : }
44 : }
|