Skip to content

Instantly share code, notes, and snippets.

@harunkurtdev
Forked from corenel/README.md
Created August 29, 2023 10:05
Show Gist options
  • Save harunkurtdev/aaa2e7019f65988af92800428e5fe4aa to your computer and use it in GitHub Desktop.
Save harunkurtdev/aaa2e7019f65988af92800428e5fe4aa to your computer and use it in GitHub Desktop.
RTSP Port Forwarding

之前在这里研究过的用iptables配置跨网段的端口转发

Assume we have the following network environments:

  • Device:
    • eth0 (192.168.6.59): for external access
    • enx000ec6a490c5 (192.168.1.2): for ip camera
  • IP Camera:192.168.1.10
  • PC:192.168.6.2

On Device, we want to forward the 554 port (used for RTSP) in ip camera (192.168.1.10) to the same port in 192.168.6.59.

  1. Run script/enable_port_forwarding.sh

    #!/usr/bin/env bash
    
    enable_forwarding () {
      ip=$1
      port=$2
      nic=$3
    
      # forward traffic from interface eth0 (public ethernet) and port 554 to the ip camera (192.168.1.10:554)
      sudo iptables -t nat -A PREROUTING -p tcp -i ${nic} --dport ${port} -j DNAT --to-destination ${ip}:${port}
      sudo iptables -t nat -A PREROUTING -p udp -i ${nic} --dport ${port} -j DNAT --to-destination ${ip}:${port}
    
      # accept traffic from ip camera
      sudo iptables -A FORWARD -p tcp -d ${ip} --dport ${port} -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
    }
    
    # parameters
    INTERNAL_IP=192.168.1.10 # for IP camera connected to Host
    PUBLIC_NIC=eth0 # for NIC connected to Internet
    # enable ipv4 forwarding in system side
    sudo sysctl net.ipv4.ip_forward=1
    # flush existed rules of iptables
    sudo iptables -F
    sudo iptables -t nat -F
    sudo iptables -X
    # enable port forwarding
    enable_forwarding ${INTERNAL_IP} 80 ${PUBLIC_NIC}
    enable_forwarding ${INTERNAL_IP} 554 ${PUBLIC_NIC}
    # enable routing
    sudo iptables -t nat -A POSTROUTING -j MASQUERADE
  2. You can use the following command to play forwarded RTSP stream on PC:

    ffplay -hide_banner -rtsp_transport tcp "rtsp://192.168.6.59:554/user=admin&password=&channel=1&stream=0.sdp?"
    
  3. But you still need to use the original url (like rtsp://192.168.1.10:554/user=admin&password=&channel=1&stream=0.sdp?) to receive video stream on Device.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment