tags:

views:

65

answers:

2

Suppose I have made two connections in Perl with the help of IO::Socket. The first has socket $s1 and the second has socket $s2.

Any ideas how can I connect them together so that whatever gets received from $s1 got sent to $s2 and whatever gets received from $s2 got sent to $s1?

I can't understand how to do it. I don't know how to connect them together. I would expect to do something like $s1->stdin = $s2->stdout and $s2->stdin = $s1->stdout, but there are no such constructs in Perl.

Please help me!

Thanks, Boda Cydo.

+2  A: 

How about

$s2->print( $_ ) while <$s1>;
friedo
That is not correct. <> acts on text streams and not binary data. And it doesn't connect anything, it's a one-time thing.
bodacydo
`<>` works just fine on sockets, which are `IO::Handle` objects.
friedo
There is, in fact, no way to "connect" two sockets. You have to read from the first one (sysread is better than readline), and write that data to the other one. (There is a sendfile system call that connects two descriptors, but one has to be a disk file.) What are you actually trying to achieve?
jrockway
jrockway, i am trying to create a program that i can monitor my web usage.
bodacydo
so when i make a connection to web, i want this program to be between me and the web.
bodacydo
+5  A: 

If you are dealing with binary data, you need to know what size chunks to read and write. Lets say you are dealing with 512 byte chunks:

my $buffer;
while (read $s1 => $buffer, 512) { # read up to 512 bytes
    print $s2 $buffer;
} 

I am not sure if pipe works with sockets, but if so:

pipe $s1 => $s2;
pipe $s2 => $s1;

"might" work. I don't have much experience with the pipe function.

Edit:

As mentioned in a comment, you seem to be trying to create an HTTP proxy. CPAN already has several modules that can do this for you. A quick search turns up:

Eric Strom
Thanks, HTTP::Proxy worked!
bodacydo