如何路由数据包以使用 localhost 作为网关?
我正在尝试测试我编写的网关(请参阅什么是最简单的方法测试网关?了解上下文)。由于我不想讨论的问题,网关和“发送者”必须位于同一台计算机上。我有一个网关能够到达的接收器(假设是 9.9.9.9)。
因此,我将运行一个应用程序 ./sendStuff 9.9.9.9
,它将向该 IP 地址发送一些数据包。
问题是:如何让发往 9.9.9.9 的数据包到达本地主机上的网关?我试过:
sudo route add -host 9.9.9.9 gw 127.0.0.1 lo
sudo route add -host 9.9.9.9 gw <机器的外部IP地址> eth0
但这些都没有通过网关传递数据包。我已验证 sudo Route
中存在正确的 IP。我能做些什么?
根据请求,运行第二个命令后,这是路由表(IP 地址已更改以匹配问题。xyzt 是我运行该命令的计算机的 IP):
Destination Gateway Genmask Flags Metric Ref Use Iface
9.9.9.9 x.y.z.t 255.255.255.255 UGH 0 0 0 eth0
x.y.z.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0
0.0.0.0 <gateway addr> 0.0.0.0 UG 100 0 0 eth0
I'm trying to test a gateway I wrote(see What's the easiest way to test a gateway? for context). Due to an issue I'd rather not get into, the gateway and "sender" have to be on the same machine. I have a receiver(let's say 9.9.9.9) which the gateway is able to reach.
So I'll run an application ./sendStuff 9.9.9.9
which will send some packets to that IP address.
The problem is: how do I get the packets destined for 9.9.9.9 to go to the gateway on localhost? I've tried:
sudo route add -host 9.9.9.9 gw 127.0.0.1 lo
sudo route add -host 9.9.9.9 gw <machine's external IP address> eth0
but neither of those pass packets through the gateway. I've verified that the correct IPs are present in sudo route
. What can I do?
Per request, here is the route table, after running the second command(IP addresses changed to match the question. x.y.z.t is the IP of the machine I'm running this on):
Destination Gateway Genmask Flags Metric Ref Use Iface
9.9.9.9 x.y.z.t 255.255.255.255 UGH 0 0 0 eth0
x.y.z.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0
0.0.0.0 <gateway addr> 0.0.0.0 UG 100 0 0 eth0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果启用了 ipv4 数据包转发,127.0.0.1 可能正在接收数据包,然后以愉快的方式转发它们。如果未启用,则会丢弃它们。
如果您尝试将发往 9.9.9.9 的数据包转发到 127.0.0.1,请查看 iptables。
编辑:试试这个:
这应该将所有流量重定向到 9.9.9.9 到 localhost。
127.0.0.1 is probably picking up the packets, then forwarding them on their merry way if ipv4 packet forwarding is enabled. If it's not enabled, it will drop them.
If you are trying to forward packets destined to 9.9.9.9 to 127.0.0.1, look into iptables.
Edit: try this:
That should redirect all traffic to 9.9.9.9 to localhost instead.