gpt4 book ai didi

iptables - 如何使用iptables进行本地端口转发

转载 作者:行者123 更新时间:2023-12-03 01:17:22 24 4
gpt4 key购买 nike

我有一个应用程序(服务器)正在监听端口 8080。我希望能够将端口 80 转发给它,以便点击 http://localhost 解析我的应用程序(在 本地主机:8080)。

这应该适用于任何端口映射(例如 80:8080 => P_src:P_target),并使用现代 *nix 机器(例如 Ubuntu)的最佳实践.

注意这一切都是在本地完成的,因此不需要接受除本地主机之外的任何人的连接。

最佳答案

经过大量搜索后,我发现答案是使用 iptables、设置 NAT 并使用内置的 PREROUTING 和 OUTPUT。

首先,您必须启用端口转发:

echo "1">/proc/sys/net/ipv4/ip_forward

然后,您必须使用您自己的 ${P_src}${P_target} 值将以下规则添加到 iptables NAT 表中:

iptables -t nat -A PREROUTING -s 127.0.0.1 -p tcp --dport ${P_src} -j REDIRECT --to ${P_target}`
iptables -t nat -A OUTPUT -s 127.0.0.1 -p tcp --dport ${P_src} -j REDIRECT --to ${P_target}`

如果您想删除规则,只需对每个规则使用 -D 开关而不是 -A 即可。

我为此构建了一个很好的小脚本,用于添加和删除映射。

#!/bin/bash
#
# API: ./forwardPorts.sh add|rm p1:p1' p2:p2' ...
#
# Results in the appending (-A) or deleting (-D) of iptable rule pairs that
# would otherwise facilitate port forwarding.
#
# E.g
# sudo iptables -t nat -A PREROUTING -s 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to 8080
# sudo iptables -t nat -A OUTPUT -s 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to 8080
#

if [[ $# -lt 2 ]]; then
echo "forwardPorts takes a state (i.e. add or rm) and any number port mappings (e.g. 80:8080)";
exit 1;
fi

case $1 in
add )
append_or_delete=A;;
rm )
append_or_delete=D;;
* )
echo "forwardPorts requires a state (i.e. add or rm) as it's first argument";
exit 1; ;;
esac

shift 1;

# Do a quick check to make sure all mappings are integers
# Many thanks to S.O. for clever string splitting:
# http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash
for map in "$@"
do
IFS=: read -a from_to_array <<< "$map"
if [[ ! ${from_to_array[0]} =~ ^-?[0-9]+$ ]] || [[ ! ${from_to_array[1]} =~ ^-?[0-9]+$ ]]; then
echo "forwardPorts port maps must go from an integer, to an integer (e.g. 443:4443)";
exit 1;
fi
mappings[${#mappings[@]}]=${map}
done

# We're shooting for transactional consistency. Only manipulate iptables if all
# the rules have a chance to succeed.
for map in "${mappings[@]}"
do
IFS=: read -a from_to_array <<< "$map"
from=${from_to_array[0]}
to=${from_to_array[1]}

sudo iptables -t nat -$append_or_delete PREROUTING -s 127.0.0.1 -p tcp --dport $from -j REDIRECT --to $to
sudo iptables -t nat -$append_or_delete OUTPUT -s 127.0.0.1 -p tcp --dport $from -j REDIRECT --to $to
done

exit 0;

关于iptables - 如何使用iptables进行本地端口转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28170004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com