#!/usr/bin/perl

use strict;
use warnings;
use File::Slurp qw( read_dir );
use IO::Socket::Multicast;
#use Data::Dumper;

my $port = 31101;
my $group = '225.0.0.1';

while (1) {
  #print STDERR "$0 Loop...\n";

  eval {
    my $ips = _get_ips();
    die "Can't find ips in the machine..." unless scalar @$ips;
    my $ip_addr = $ips->[0];

    my $s = IO::Socket::Multicast->new( LocalPort => $port );
    # Turn off loopbacking
    $s->mcast_loopback(0);
    # Set time to live on outgoing multicast packets
    $s->mcast_ttl(10);
    # send message
    $s->mcast_send($ip_addr, "$group:$port");
  };

  if ($@) {
    print STDERR "ERROR - $@\n";
  }

  sleep 5;
}

#
# Functions
#

sub _get_ips {
  my @devices = read_dir('/sys/class/net');
  my $ip_addr = "";

  #my $gateway_info = _get_gateway();

  my @ips = ();

  foreach my $dev (sort @devices) {
    next if $dev eq 'lo' || $dev =~ /tun/;
    my $cnt = `ip addr show $dev | grep "inet "`;
    chop($cnt);
    next unless $cnt;
    my( $ip ) = $cnt =~ /inet (\d+\.\d+\.\d+\.\d+)/;
    push @ips, $ip;
  }

  return \@ips;
}

sub _get_gateway {
  my $prefix = shift;

  my $ref = {};

  my $gateway = `ip route | grep default | awk '{ print \$3 }'`;
  $gateway //= "";

  if ($gateway) {
    my @g = split /\n/, $gateway;

    foreach my $g (@g) {
      my( $ip ) = $g =~ /^(\d+)\./;
      $ref->{$ip} = $g;
    }
  }

  return $ref;
}

