Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there simple descriptions on port forwarding using python?

I can do simply socket communication on the same machine using

server:

import socket

s = socket.socket()
host = socket.socket()
port = 8000
s.bind((host,port))
s.listen(5)
while true:
     c,addr = s.accept()
     print 'got connection from', addr
     c.send('thank you for connecting')
     c.close()

client:

import socket 

s = socket.socket()
host=socket.gethostname()
port = 8000
s.connect((host,port))
print s.recv(1024)

What changes would need to be made have this communicate between my laptop and a private server I work on? I have figured from my searching that portforwarding is the best way to go about it but haven't found any explanations or tutorials on how to go about it.

thank you

like image 387
GreatGather Avatar asked Jul 05 '12 18:07

GreatGather


Video Answer


2 Answers

If you don't really need to do this in python, just use netcat: -

http://netcat.sourceforge.net/

Port Forwarding or Port Mapping On Linux, NetCat can be used for port forwarding. Below are nine different ways to do port forwarding in NetCat (-c switch not supported though - these work with the 'ncat' incarnation of netcat):

nc -l -p port1 -c ' nc -l -p port2'
nc -l -p port1 -c ' nc host2 port2'
nc -l -p port1 -c ' nc -u -l -p port2'
nc -l -p port1 -c ' nc -u host2 port2'
nc host1 port1 -c ' nc host2 port2'
nc host1 port1 -c ' nc -u -l -p port2'
nc host1 port1 -c ' nc -u host2 port2'
nc -u -l -p port1 -c ' nc -u -l -p port2'
nc -u -l -p port1 -c ' nc -u host2 port2'

Source: - http://en.wikipedia.org/wiki/Netcat#Port_Forwarding_or_Port_Mapping

It usually comes as standard on most *nix distributions and there is also a Win32 port: -

http://www.stuartaxon.com/2008/05/22/netcat-in-windows/

like image 161
Jason Avatar answered Oct 17 '22 14:10

Jason


If you care about Python port forwarding implementation, there's an old but great ActriveState recipe that implements asynchronous port forwarding server using only Python standard library (socket, asyncore). You can poke around at code.activestate.com.

P.S. There's also a link to a threaded version of the script.

like image 45
Rostyslav Dzinko Avatar answered Oct 17 '22 14:10

Rostyslav Dzinko