Created
January 12, 2016 19:22
-
-
Save chadspencer/035df97c39f89e7cb7ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl -w | |
# usage: portforward 18025:mail.messagingengine.com:25 | |
#where 18025 is the TCP port on the local machine and | |
# mail.messagingengine.com:25 is where that port is forwarded to. | |
# Based on: http://www.perlmonks.org/bare/?node_id=367253 | |
use Socket; | |
use IO::Socket; | |
use IO::Select; | |
use strict; | |
$| = 1; | |
$SIG{CHLD} = 'IGNORE'; | |
my ($localport, $remotehost) = split(':',$ARGV[0],2); | |
my $socklisten = IO::Socket::INET->new(LocalPort => $localport, | |
Listen => 2, | |
Reuse => 1, | |
Proto => 'tcp') | |
or die "Cannot open sock on $localport: $!\n"; | |
print "Parent ready to accept\n"; | |
while (1) { | |
my $socklocal = $socklisten->accept; | |
if (defined $socklocal) { | |
my ($port, $myaddr) = sockaddr_in(getsockname($socklisten)); | |
print "accepted on $port\n"; | |
if (fork()) { | |
close($socklocal); | |
} else { | |
close($socklisten); | |
my $sockremote = IO::Socket::INET->new( | |
Proto => "tcp", | |
PeerAddr => "$remotehost", | |
Timeout => 30, | |
) or die "cannot create socketremote($remotehost): $!\n"; | |
my $buf= ' 'x4096; | |
if (fork()) { | |
my $sent = 0; | |
while (sysread($socklocal, $buf, 4096)) { | |
print $sockremote $buf; | |
$sent += length($buf); | |
} | |
} else { | |
my $rcvd = 0; | |
while(sysread($sockremote, $buf, 4096)) { | |
print $socklocal $buf; | |
$rcvd += length($buf); | |
} | |
} | |
exit(0); } } } | |
print "End of parent: $!\n"; | |
__END__ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment