什么是内网穿透? 众所周知,得益于 NAT(Network Address Translator 网络地址转换)技术的存在,使得全球互联网可连接的计算机数能够远远超过 43 亿台。其原理就是在本地网络中使用私有地址(内网 IP),在连接互联网时使转而使用全局 IP 地址(公网 IP),这样,多个计算机就可以共用一个 IP 地址,从而达到减缓 IPV4 地址损耗的目的。
大伙可以打开命令行输入 ifconfig | grep inet 找到自己的内网 IP 地址,你的 IP 一定是在 192.168.0.0~192.168.255.255 这个区间里面,这是因为 TCP/IP 协议专门设定了内网 IP 地址的范围:
A 类 - 10.0.0.0/8:10.0.0.0~10.255.255.255 B 类 - 172.16.0.0/12:172.16.0.0~172.31.255.255 C 类 - 192.168.0.0/16:192.168.0.0~192.168.255.255 仅靠这个内网 IP 地址是无法上网的,需要通过 NAT 路由器转成公网 IP 才行,可以通过 curl cip.cc 来查看自己电脑的出口公网 IP 地址。
那这时候可能有小伙伴要问了,NAT 路由器不是会将内网 IP 转成公网 IP 吗?直接通过个 公网 IP:端口号 难道不能访问这个本地服务吗?
很遗憾,不能。
使用 NAT 绑定的公网 IP 直接进行访问,就意味着所有请求的 IP 报文中的目的 IP 地址都是这个公网 IP,那么 NAT 路由器无法区分这个请求到底要转发到内网的哪一台机器,这会导致端口冲突问题。
因此,如果这个时候你想要把这个服务开放给互联网上的其他人进行访问,你有两种方案:
将该服务部署到云服务器
内网穿透,将当前的内网 IP 和一个可访问的公网 IP 建立联系,使得别人可以通过公网 IP 访问你的本地主机 本地服务开放给公网访问这个需求在做微信开发的时候还是非常常见的,因为微信的各种回调函数都要求是公网可以访问的地址,总不能每在本地改一次代码就部署一次云服务器吧,不说费时间了,调试起来也很麻烦,所以内网穿透还是非常必要的。
说了这么多,总结下什么是内网穿透?
一般情况下,私有网络中的计算机无法被公网访问,因为它们的 IP 地址是内网 IP,不能直接被公网访问。内网穿透技术通过将公网上的请求转发到内网中的计算机上,从而实现了内网计算机与外网之间的数据通信。内网穿透技术主要应用于需要远程控制、远程访问、文件共享等场景,以便在安全性、便捷性和实用性方面取得平衡。
2023-10-05T08:23:57Z INF Starting tunnel tunnelID=4be1826f-c58b-4184-9b6d-1789d0395715 2023-10-05T08:23:57Z INF Version 2023.8.2 2023-10-05T08:23:57Z INF GOOS: windows, GOVersion: go1.20.6, GoArch: amd64 2023-10-05T08:23:57Z INF Settings: map[no-autoupdate:true token:***** url:http://127.0.0.1:5200] 2023-10-05T08:23:57Z INF cloudflared will not automatically update on Windows systems. 2023-10-05T08:23:57Z INF Generated Connector ID: cceee48e-8705-4429-a886-7170dc75b683 2023-10-05T08:23:57Z INF Initial protocol quic 2023-10-05T08:23:57Z INF ICMP proxy will use 10.27.214.21 as source for IPv4 2023-10-05T08:23:58Z INF ICMP proxy will use 2001:da8:7001:2000::7a8b in zone WLAN as source for IPv6 2023-10-05T08:23:58Z INF cloudflared does not support loading the system root certificate pool on Windows. Please use --origin-ca-pool <PATH> to specify the path to the certificate pool 2023-10-05T08:23:58Z INF Starting metrics server on 127.0.0.1:53456/metrics 2023-10-05T08:24:03Z INF
=================================================================================== You are hitting an error while using the experimental post-quantum tunnels feature.
Please check:
https://pqtunnels.cloudflareresearch.com
for known problems. ===================================================================================
2023-10-05T08:24:03Z ERR Failed to create new quic connection error="failed to dial to edge with quic: timeout: no recent network activity" connIndex=0 event=0 ip=198.41.200.73 2023-10-05T08:24:03Z INF Retrying connection in up to 2s connIndex=0 event=0 ip=198.41.200.73 2023-10-05T08:24:09Z ERR Failed to create new quic connection error="failed to dial to edge with quic: timeout: no recent network activity" connIndex=0 event=0 ip=198.41.192.77 2023-10-05T08:24:09Z INF Retrying connection in up to 4s connIndex=0 event=0 ip=198.41.192.77