I have the following subroutine:
use Socket
...
sub proxy_connect {
my $iaddr = Socket::inet_aton($proxy);
my $paddr = Socket::sockaddr_in(81, $iaddr);
my $proto = getprotobyname('tcp');
my $fh = new FileHandle;
socket($fh, PF_INET, SOCK_STREAM, $proto) or return;
connect($fh, $paddr) or return;
$fh->autoflush(1);
# return a pointer to file handle
return \$fh;
}
my $mysock = proxy_connect();
The Python approach is totally different, and instead of returning a File object I return a socket, but I am not sure the functionality is exactly the same:
import socket
...
def proxy_connect():
"""
Connect to the proxy and return a filehandle for it.
"""
proxy = "proxy.mydomain.com"
address = socket.gethostbyname(proxy)
con = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
con.connect((address, 81))
return con
Am I on the right path to translating this tunnel-ssh-over-http?
Note, I am quite novice in Perl, and this just done as an exercise to learn some more stuff about Perl and sockets (in Python).
Yes, you can do a straight forward conversion. select() will behave the same in Python, allowing you to test for data-ready-to-read on the sockets. In Perl, they are using vec() but in Python you test whether your socket is in the return value of select(). In Perl where they sysread/syswrite you would instead use socket.recv() socket.send()
The do_copy routine is almost a straight translation, except that socket.send() doesn’t take an offset/len, so you will need to slice the buffer yourself if socket.send() doesn’t indicate the entire buffer was sent.
The SELECT loop will work the same way as in the perl code. You’ll pass in the sockets you want to test for readability, and do something like: