查询公网IP

更新:已上传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/88744119icon-default.png?t=N7T8https://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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值