Skip to content

Instantly share code, notes, and snippets.

@yareally
Created August 17, 2016 06:13
Show Gist options
  • Save yareally/aaec0c6172ac1e35aa6f8ed3bf92d91a to your computer and use it in GitHub Desktop.
Save yareally/aaec0c6172ac1e35aa6f8ed3bf92d91a to your computer and use it in GitHub Desktop.
old school lab
#!/usr/local/bin/perl -w
use strict;
use IO::Socket::INET;
use Sys::Hostname;
use Data::Dumper;
my ($remote_host, $remote_port);
$remote_port = $ARGV[0];
my $hostname = `hostname`;
print $hostname."\n";
my $server = IO::Socket::INET->new(Proto => 'tcp',
LocalPort => $remote_port,
Listen => SOMAXCONN,
Reuse => 1 ) or die $@;
my $client;
while ($client = $server->accept()) {
my %clientValues;
while (my $stuff = <$client>) {
chomp $stuff;
$stuff =~ s/\s+$//;
if ($stuff =~ /^(\w+): (\d+)/) {
$clientValues{$1} = $2;
}
elsif ($stuff =~ /DONE/) {
print "The client told us we were done\n";
last;
}
}
my $key;
foreach $key (sort keys %clientValues) {
print "$key => $clientValues{$key}\n";
}
print "\n";
foreach $key (sort {$clientValues{$a} <=> $clientValues{$b} } keys %clientValues) {
print "$key => $clientValues{$key}\n";
}
print "\n";
#readLines($client);
close($client);
close($server);
}
sub readLines {
my $client = shift(@_);
}
# ----------- Client ------------
#!/usr/local/bin/perl -w
use strict;
use IO::Socket::INET;
my ($remote_host, $remote_port);
$remote_host = $ARGV[0];
$remote_port = $ARGV[1];
my $file = $ARGV[2];
my $line = '';
my $fh;
my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,
PeerPort => $remote_port,
Proto => "tcp")
or die "Couldn't connect to $remote_host:$remote_port : $!\n";
$socket->autoflush(1);
#required for server.pl issue with filling buffer while accepting connections
print $socket "\n";
if (validFile($file)) {
open($fh, $file) or die "$file cannot be opened.";
my @contents = <$fh>;
foreach $line(@contents) {
print $socket $line;
}
}
while (my $line = <$socket>) {
print $line;
}
close ($socket);
sub validFile {
my $file = shift(@_);
if (!(-e $file)) {
print "File: $file DNE";
exit(1);
}
elsif (-z $file) {
print "File: $file exists, but size is zero";
exit(1);
}
elsif (!(-r $file)) {
print "File: $file is not readable";
exit(1);
}
elsif (-B $file) {
print "File: $file is not a text file";
exit(1);
}
else {
return 1; #good file input
}
return 0; #some uncaught error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment