Skip to content

Instantly share code, notes, and snippets.

@corenel
Last active February 29, 2024 21:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save corenel/db98113b346717e114864538996134a8 to your computer and use it in GitHub Desktop.
Save corenel/db98113b346717e114864538996134a8 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.

@julianoes
Copy link

This is useful, thanks! Do you know why -rtsp_transport tcp is required and whether there is a way to do it without?

@julianoes
Copy link

For anyone finding this and wondering how to get UDP transport to work, here is my updated fork of this gist:
https://gist.github.com/julianoes/0555ee982991fe97e5a4c2b11316195f

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