+sub tcp_ping {
+ my ($host, $port, $timeout) = @_;
+
+ my $refused = 1;
+
+ $timeout = 3 if !$timeout; # sane default
+ if (!$port) {
+ # Net::Ping defaults to the echo port
+ $port = 7;
+ } else {
+ # Net::Ping's port_number() implies service_check(1)
+ $refused = 0;
+ }
+
+ my ($sock, $result);
+ eval {
+ $result = PVE::Tools::run_with_timeout($timeout, sub {
+ $sock = IO::Socket::IP->new(PeerHost => $host, PeerPort => $port, Type => SOCK_STREAM);
+ $result = $refused if $! == ECONNREFUSED;
+ });
+ };
+ if ($sock) {
+ $sock->close();
+ $result = 1;
+ }
+ return $result;
+}
+
+sub IP_from_cidr {
+ my ($cidr, $version) = @_;
+
+ return if $cidr !~ m!^(\S+?)/(\S+)$!;
+ my ($ip, $prefix) = ($1, $2);
+
+ my $ipobj = Net::IP->new($ip, $version);
+ return if !$ipobj;
+
+ $version = $ipobj->version();
+
+ my $binmask = Net::IP::ip_get_mask($prefix, $version);
+ return if !$binmask;
+
+ my $masked_binip = $ipobj->binip() & $binmask;
+ my $masked_ip = Net::IP::ip_bintoip($masked_binip, $version);
+ return Net::IP->new("$masked_ip/$prefix");
+}
+
+sub is_ip_in_cidr {
+ my ($ip, $cidr, $version) = @_;
+
+ my $cidr_obj = IP_from_cidr($cidr, $version);
+ return undef if !$cidr_obj;
+
+ my $ip_obj = Net::IP->new($ip, $version);
+ return undef if !$ip_obj;
+
+ return $cidr_obj->overlaps($ip_obj) == $Net::IP::IP_B_IN_A_OVERLAP;
+}
+
+# struct ifreq { // FOR SIOCGIFFLAGS:
+# char ifrn_name[IFNAMSIZ]
+# short ifru_flags
+# };
+my $STRUCT_IFREQ_SIOCGIFFLAGS = 'Z' . IFNAMSIZ . 's1';
+sub get_active_interfaces {
+ # Use the interface name list from /proc/net/dev
+ open my $fh, '<', '/proc/net/dev'
+ or die "failed to open /proc/net/dev: $!\n";
+ # And filter by IFF_UP flag fetched via a PF_INET6 socket ioctl:
+ my $sock;
+ socket($sock, PF_INET6, SOCK_DGRAM, &IPPROTO_IP)
+ or socket($sock, PF_INET, SOCK_DGRAM, &IPPROTO_IP)
+ or return [];
+
+ my $ifaces = [];
+ while(defined(my $line = <$fh>)) {
+ next if $line !~ /^\s*([^:\s]+):/;
+ my $ifname = $1;
+ my $ifreq = pack($STRUCT_IFREQ_SIOCGIFFLAGS, $ifname, 0);
+ if (!defined(ioctl($sock, SIOCGIFFLAGS, $ifreq))) {
+ warn "failed to get interface flags for: $ifname\n";
+ next;
+ }
+ my ($name, $flags) = unpack($STRUCT_IFREQ_SIOCGIFFLAGS, $ifreq);
+ push @$ifaces, $ifname if ($flags & IFF_UP);
+ }
+ close $fh;
+ close $sock;
+ return $ifaces;
+}
+