赞
踩
- import socket
- # 函数 gethostname() 返回当前正在执行 Python 的系统主机名
- res = socket.gethostbyname(socket.gethostname())
- print(res)
- import socket
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s.connect(("8.8.8.8", 80))
- print(s.getsockname()[0])
注意:如果本身局域网IP就是公网IP的话,那这个获得的,可以认为是公网IP了。
- import socket
- def extract_ip():
- st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- st.connect(('10.255.255.255', 1))
- IP = st.getsockname()[0]
- except Exception:
- IP = '127.0.0.1'
- finally:
- st.close()
- return IP
- print(extract_ip())
netifaces 模块用于提供有关网络接口及其状态的信息。
没有使用过的先装一下库
pip3 install netifaces
然后使用
- from netifaces import interfaces, ifaddresses, AF_INET
- for ifaceName in interfaces():
- addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
- print(' '.join(addresses))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。