use PVE::ProcFSTools;
use PVE::INotify;
use File::Basename;
+use IO::Socket::IP;
+use POSIX qw(ECONNREFUSED);
+
+use Net::IP;
# host network related utility functions
my @ifaces = ();
my $dir = "/sys/class/net/$bridge/brif";
- PVE::Tools::dir_glob_foreach($dir, '((eth|bond)\d+)', sub {
+ PVE::Tools::dir_glob_foreach($dir, '((eth|bond)\d+(\.\d+)?)', sub {
push @ifaces, $_[0];
});
return $bridgevlan;
}
+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;
+}
+
1;