How to use ncat or socat to map the remote port to local server


Introduction

ncat和socat都是linux的網路工具
這次主題要達成的目標用這兩個都能達成

他們可以做到: 只要是能夠訪問到的port都可以把它映射到本機的port上

寫這篇也是要介紹之前寫reverse proxy的文章的額外補充

docker瞬間佈署reverse proxy還有SSL認證

那篇是以frp做到內網穿透,而另一個方法是結合ncat和zerotier達到相同效果
目標都是把遠端的port映射到本機的port

Check the port whether is reachable

首先先確認遠端的server的服務是否可訪問

nc -zv [server ip] [port]

以圖中為例,指令會是

nc -zv 192.168.1.2 80

可訪問的話就會回傳

Connection to 192.168.1.2 80 port [tcp/http] succeeded!  

How to Check Remote Ports are Reachable Using ‘nc’ Command

Mapping the port to local server

接下來就是用socat或ncat將192.168.1.2:80映射到localhost:8080 (192.168.1.1:8080)

socat version

socat tcp-l:${LOCAL_PORT},fork,reuseaddr tcp:${SERVER_IP}:${SERVER_PORT}

Example:

socat tcp-l:8080,fork,reuseaddr tcp:192.168.1.2:80

ncat version

ncat --sh-exec "ncat $SERVER_IP $SERVER_PORT" -l $LOCAL_PORT --keep-open

Example:

ncat --sh-exec "ncat 192.168.1.2 80" -l 8080 --keep-open

docker version

兩個工具我都有用docker容器化成只要用docker-compose就能啟用

docker pull hunglin59638/socat

設定好.env的變數就能使用了

git clone https://github.com/hunglin59638/dockerfiles.git  
cd socat-tunnel
docker-comose up -d

https://github.com/hunglin59638/dockerfiles/tree/master/socat-tunnel
https://github.com/hunglin59638/dockerfiles/tree/master/ncat-tunnel


Author: Hung-Lin, Chen
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Hung-Lin, Chen !
  TOC