如何在Python平台中独立地找到本地IP地址(即192.168.xx或10.0.xx)并仅使用标准库?
我知道这个话题并不新鲜。尽管有各种信息,但没有提供可靠的解决方案(至少我没有找到)。我有一个用 python3 编写的 P2P 守护进程,最后一个元素是通过 TCP 连接 NAT 后面的两个客户端。我对这个主题的参考:
https://bford.info/pub/net/p2pnat/
在两个客户端都连接了会议点服务器后,如何使两个客户端直接相互连接?
到目前为止我所做的:
服务器:
#!/usr/bin/env python3
import threading
import socket
MY_AS_SERVER_PORT = 9001
TIMEOUT = 120.0
BUFFER_SIZE = 4096
def get_my_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return bytes(IP, encoding='utf-8')
def wait_for_msg(new_connection, client_address):
while True:
try:
packet = new_connection.recv(BUFFER_SIZE)
if packet:
msg_from_client = packet.decode('utf-8')
client_connected_from_ip = client_address[0]
client_connected_from_port = client_address[1]
print("We have …Run Code Online (Sandbox Code Playgroud) 我试图了解Hop期间IP数据包发生了什么样的结构变化.
请允许我以示例解释我的问题.
traceroute -w 1 google.com
traceroute to google.com (216.58.199.174), 64 hops max, 52 byte packets
1 192.168.0.1 (192.168.0.1) 1.055 ms 0.857 ms 0.822 ms
2 10.0.0.1 (10.0.0.1) 2.038 ms 1.477 ms 1.540 ms
3 * * *
4 114.79.130.1.dvois.com (114.79.130.1) 3.091 ms 2.076 ms 2.329 ms
5 10.241.1.6 (10.241.1.6) 3.245 ms 3.102 ms 3.358 ms
6 10.240.254.140 (10.240.254.140) 4.388 ms 2.149 ms 2.319 ms
7 10.240.254.1 (10.240.254.1) 3.067 ms 3.336 ms 2.852 ms
8 10.241.1.1 (10.241.1.1) 2.542 ms 2.339 …Run Code Online (Sandbox Code Playgroud) networking ×2
python ×2
ip-address ×1
ipv4 ×1
mac-address ×1
nat ×1
routing ×1
sockets ×1
tcp ×1
tcp-ip ×1