#!/usr/bin/perl
use warnings;
use strict;
use Socket;
use POE;
use IO::Socket::INET;

use constant DATAGRAM_MAXLEN => 1024;

POE::Session->create(
    inline_states => {
        _start       => \&server_start,
        get_datagram => \&server_read,
      }
);

POE::Kernel->run();
exit;

sub server_start {
    my $kernel = $_[KERNEL];

    my $socket = IO::Socket::INET->new(
        Proto     => 'udp',
        LocalPort => '1234',
    );

    die "Couldn't create server socket: $!" unless $socket;
    $kernel->select_read( $socket, "get_datagram" );
}

sub server_read {
    my ( $kernel, $socket ) = @_[ KERNEL, ARG0 ];
    my $remote_address = recv( $socket, my $message = "", DATAGRAM_MAXLEN, 0 );
    return unless defined $remote_address;
    my ( $peer_port, $peer_addr ) = unpack_sockaddr_in($remote_address);
    my $human_addr = inet_ntoa($peer_addr);
    print "(client) $human_addr:$peer_port sent us $message\n";
    my $hexed = unpack "H*", inet_aton("$human_addr");
    my $ported = unpack "H*", inet_aton("$peer_port");
    $ported =~ s/0000//;
    $message =~ s/"//;
    $message =~ s/(.*?)#//;
    $message  =~ s/(.|\n)/sprintf("%02lx", ord $1)/eg;
    my $ping = "0042";
    my $ff = "ff";
    my $start = "23";
    my $hexme = "$start$message$hexed$ported$ping$ff$ff$ff$ff";
    $hexme =~ s/([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    my $complete = "$hexme";
    print "(server) sending $complete\n";
    send( $socket, $complete, 0, $remote_address )
}


