GreatGather
GreatGather

Reputation: 881

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

Upvotes: 6

Views: 4062

Answers (2)

Jason
Jason

Reputation: 373

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/

Upvotes: 2

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40765

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.

Upvotes: 1

Related Questions