Port forwarding functions

Home   »   Port forwarding functions

#!/bin/bash 

# Put the file to: /etc/profile.d/

port-forward(){
  local port=\$1
  local to_ip=\$2
  if [ -z \${port} ] || [ -z \${to_ip} ]; then
    echo "Usage: port-forward [port] [destination ip]"
    return
  fi

  iptables -A PREROUTING -t nat -p tcp --dport \${port} -j DNAT --to \${to_ip}:\${port}
  iptables -A FORWARD -p tcp -m state --state NEW --dport \${port} -j ACCEPT
  #iptables -t nat -A POSTROUTING -j MASQUERADE -o eth0
}
# add content to PowerShell profile

function wsl-route {
	$subnet = "10.254.0.0"
	$wsl_ip = wsl myip
	$p = Start-Process route -Verb runAs -ArgumentList "ADD ${subnet} MASK 255.255.255.0 ${wsl_ip}" -PassThru -Wait
	$code_str = if ($p.ExitCode -eq 0) {"OK"} else {"FAIL"}
	Write-Host "Routing ${subnet} subnet via ${wsl_ip}  ... ${code_str}" 
}

function get-my-ip(){
	$p = (
	 Get-NetIPConfiguration |
		Where-Object {
			$null -ne $_.IPv4DefaultGateway -and
			$_.NetAdapter.Status -ne "Disconnected"
		}
	)
	
	   return  New-Object -Type PSObject -Property @{
		   'ip' = $p.IPv4Address.IPAddress
		   'dev' =$p.IPv4Address.InterfaceAlias
	   }
 }


  function port-forward($port, $target){
	$myip=get-my-ip
   
    $p = Start-Process netsh -Verb runAs -ArgumentList "interface portproxy add v4tov4 listenaddress=$($myip.ip) listenport=${port} connectaddress=${target} connectport=${port}" -PassThru -Wait
	$code_str = if ($p.ExitCode -eq 0) {"OK"} else {"FAIL"}
	Write-Host "Forwarding $($myip.ip):${port} => ${target}:${port} .... ${code_str}"
   }

Leave a Reply

Your email address will not be published. Required fields are marked *