1. Port mapping (port redirection):
Intranet host port————》Extranet host port.
Access to external network port————"Intranet host port.
Set up a port mapping on the router.
One-to-one correspondence between external ports and internal ports
2. Port forwarding:
Port forwarding, sometimes called tunnel:
ip address and router port binding
One-to-one correspondence between external port and internal IP
3. Port multiplexing:
The two programs listen on the same port.
The most important function in port multiplexing technology is setsockopt()
setsockopt() function, which is used to set option values of any type and any state socket.
Set the SO_REUSEADDR option of the socket to achieve port reuse
SO_REUSEADDR: The socket is bound to multiple ports, and the port is bound to multiple sockets
1. Multiple sockets are bound to 1 port
But the IP address bound to each instance cannot be the same. (E.g. router)
import socket
tcp1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#在绑定前调用setsockopt让套接字允许地址重用
tcp1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
tcp2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
#接下来两个套接字都也可以绑定到同一个端口上
tcp1.bind(('0.0.0.0', 12345))
tcp2.bind(('0.0.0.1, 12345))
2. One socket binds multiple ports
The IP address bound to each socket is different.
Receive one port, send another port
#coding=utf-8
import socket
import sys
import select
host='192.168.1.8'
port=80
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
s.bind((host,port))
s.listen(10)
S1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
S1.connect(('127.0.0.1',3389))
print "Start Listen 80 =>3389....."while 1:
infds,outfds,errfds=select.select([s,],[],[],5) #转发3389需去除
if len(infds)!=0:#转发3389需去除
conn,(addr,port)=s.accept()
print '[*] connected from ',addr,port
data=conn.recv(4096)
S1.send(data)
recv_data=s1.recv(4096)
conn.send(recv_data)
print '[-] connected down',
S1.close()
s.close()