更新:已上传pypi,略有改动,请使用如下代码:
pip install ipv4v6
根据pystun的stuntest()函数改编的,只保留了获取公网IP的功能。可指定本地端口(要查询公网IP的端口)、stun服务器(默认为stun.l.google.com:19302),可根据需要改编或导入
(有关于pystun的更多信息,请参阅:https://blog.csdn.net/Oscar_Myh_39/article/details/135599068)
https://download.csdn.net/download/Oscar_Myh_39/88744119https://download.csdn.net/download/Oscar_Myh_39/88744119资源下载请戳上面(有积分的大佬下载一下,定价1积分,万分感谢)
好了,下面贴一下源代码(积分不够的复制代码也行):
import binascii
import random
from socket import *
def get_ip(csock:socket=None,local_port:int=8888,stun_server:str='stun.l.google.com',stun_port:int=19302):
tranid=''.join(random.choice('0123456789ABCDEF') for i in range(32))
data=binascii.a2b_hex('00010000'+tranid)
sock=None
if csock==None:
sock=socket(AF_INET,SOCK_DGRAM)
sock.bind(('0.0.0.0',local_port))
else:
sock=csock
sock.sendto(data,(stun_server,stun_port))
buf,addr=sock.recvfrom(2048)
if csock==None:
sock.close()
if tranid.upper()==binascii.b2a_hex(buf[4:20]).upper().decode() and binascii.b2a_hex(buf[0:2]).decode()=='0101':
port = int(binascii.b2a_hex(buf[26:28]), 16)
ip = ".".join([
str(int(binascii.b2a_hex(buf[28:29]), 16)),
str(int(binascii.b2a_hex(buf[29:30]), 16)),
str(int(binascii.b2a_hex(buf[30:31]), 16)),
str(int(binascii.b2a_hex(buf[31:32]), 16))
])
return (ip+':'+str(port))
return 'Failed'
def ip_tuple(csock:socket=None,local_port:int=8888,stun_server:str='stun.l.google.com',stun_port:int=19302):
ret=get_ip(csock,local_port,stun_server,stun_port)
if ret=='Failed':
return 'Failed'
ret=ret.split(':')
return (ret[0],int(ret[1]))
if __name__=='__main__':
print(get_ip())
转载请注明出处:https://blog.csdn.net/Oscar_Myh_39/article/details/135600943