In most cases you won't be able to make inbound connection when using Mobile Data because of CGNAT and firewalls at ISP level, as explained by acejavelin in comment. To know the problem in detail and how it can be worked around see How to connect to Android through SSH over 3G/4G public IP?
However if you can reach your phone from internet, extending this access to a connected host (PC in your case) is not a problem. Port forwarding is done with routers, and when being used as a Wi-Fi hotspot (or with USB tethering), your phone is in fact acting as a router.
ROOT SOLUTION:
In order to forward port, you need to do Destination Address Translation (DNAT) using Linux kernel's builtin firewall userspace tool iptables
.
First make sure that kernel is configured to forward internet traffic (already set when hotspot is ON):
~# echo 1 >/proc/sys/net/ipv4/ip_forward
Let's say the IP address assigned by hotspot to PC is 192.168.43.10
and you want to forward SSH default port (22
):
~# iptables -t nat -I PREROUTING -p tcp --dport 22 -j DNAT --to 192.168.43.10
This is the simplest form of Port Forwarding.
If default POLICY of FORWARD chain in FILTER table is not ACCEPT, define rules explicitly to accept the forwarded packets:
~# iptables -I FORWARD -p tcp -d 192.168.43.10 --dport 22 -j ACCEPT
Also accept outbound forwarded traffic if needed.
NON-ROOT SOLUTION:
On non-rooted devices you can use adb
or some other minimal TCP/UDP server like netcat
or socat
for port forwarding. Note that this won't work for ports under 1024. To forward port 2222
:
~$ adb reverse tcp:2222 tcp:2222
Or on phone:
~$ nc -lk -p 2222 -e nc 192.168.43.10 2222
* nc
is a busybox applet. But make sure that you get the right binary, there are multiple implementations of netcat
.
* Use -u
option to forward UDP port.
However nc
accepts only a single connection at a time. Use socat
or ncat
for more advanced options, e.g. from Termux:
~$ socat tcp-l:2222,fork,reuseaddr tcp:192.168.43.10:2222
See Using netcat for port forwarding.
There are also apps like Fwd (it's open-source, I have no affiliation) meant for port forwarding.
SOURCE: