Re: P2P in 15 lines

[email protected] (Brad Greenlee)
Newsgroups perl.fwp
Message-ID <[email protected]>
Ok, I bit. Spent all frickin' day on it. I stuck as close to the 
original description as possible, even adding the ability to view files 
on the network without actually downloading them, which I thought was 
pretty essential. It will also show you the size of each file.

I swapped the argument order around a bit, as I thought it was odd to 
have the password be the first parameter. Mine is invoked like so:

Server:
  perl tinyp2p.pl server <passwd> <listenhost:listenport> 
[<peerhost:peerport>]

Client:
  perl tinyp2p.pl client <passwd> <serverhost:serverport> [list|get] 
<pattern>

Note that when entering a pattern, you need to escape the backslash. So 
to search for .mp3 files, the pattern would be \\.mp3$

The result: 9 lines. If better golfers than I want to try to cut it 
down, please do. Just be forewarned that mistakes in the code can cause 
all kinds of garbage to be written to your filesystem.

Pasting it below and attaching it.

-b

# tinyp2p.pl 1.0 by Brad Greenlee <[email protected]>
# idea from http://freedom-to-tinker.com/tinyp2p.html
use IO::Socket;($t,$s,$u,$p,$x)=@ARGV;if($t 
eq"server"){$p&&($p{$p}++,map{$_ ne
$u&&$p{$_}++}f($p,2,$u));while($c=new 
IO::Socket::INET(LocalAddr=>$u,Reuse=>1,
Listen=>9)->accept()){if(<$c>eq"$s\n"){($r=<$c>)>1?do{print$c "$_\n"for 
keys%p;
chomp($a=<$c>);$a&&$p{$a}++;}:do{chomp($x=<$c>);for(grep/$x/,<*>){$z=(stat)[7];
print$c "$_\t$z\n";if($r>0){open G,$_;read G,$b,$z;close;print$c 
$b}}}}close$c}}
for$v($u,f($u,2,0)){printf"%s (%s)\n",@$_ for f($v,$p eq"get",$x)}sub 
f{($h,$q,
$m)=@_;$k=new IO::Socket::INET($h)||return;print$k 
"$s\n$q\n$m",defined$m?"\n":
'';$q>1?chomp(@r=<$k>):do{@r=();while(<$k>){chomp;($f,$e)=split/\t/;push@r,[$f,
$e]if!$q|!-e$f;next if!$q|-e$f;read$k,$b,$e;open F,">$f";print 
F$b;close}};@r}
tinyp2p.pl (text/plain, 825 B)
# tinyp2p.pl 1.0 by Brad Greenlee <[email protected]>
# idea from http://freedom-to-tinker.com/tinyp2p.html
use IO::Socket;($t,$s,$u,$p,$x)=@ARGV;if($t eq"server"){$p&&($p{$p}++,map{$_ ne
$u&&$p{$_}++}f($p,2,$u));while($c=new IO::Socket::INET(LocalAddr=>$u,Reuse=>1,
Listen=>9)->accept()){if(<$c>eq"$s\n"){($r=<$c>)>1?do{print$c "$_\n"for keys%p;
chomp($a=<$c>);$a&&$p{$a}++;}:do{chomp($x=<$c>);for(grep/$x/,<*>){$z=(stat)[7];
print$c "$_\t$z\n";if($r>0){open G,$_;read G,$b,$z;close;print$c $b}}}}close$c}}
for$v($u,f($u,2,0)){printf"%s (%s)\n",@$_ for f($v,$p eq"get",$x)}sub f{($h,$q,
$m)=@_;$k=new IO::Socket::INET($h)||return;print$k "$s\n$q\n$m",defined$m?"\n":
'';$q>1?chomp(@r=<$k>):do{@r=();while(<$k>){chomp;($f,$e)=split/\t/;push@r,[$f,
$e]if!$q|!-e$f;next if!$q|-e$f;read$k,$b,$e;open F,">$f";print F$b;close}};@r}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.