python利用標(biāo)準(zhǔn)庫(kù)如何獲取本地IP示例詳解
標(biāo)準(zhǔn)庫(kù)
Python擁有一個(gè)強(qiáng)大的標(biāo)準(zhǔn)庫(kù)。Python語(yǔ)言的核心只包含數(shù)字、字符串、列表、字典、文件等常見類型和函數(shù),而由Python標(biāo)準(zhǔn)庫(kù)提供了系統(tǒng)管理、網(wǎng)絡(luò)通信、文本處理、數(shù)據(jù)庫(kù)接口、圖形系統(tǒng)、XML處理等額外的功能。
Python標(biāo)準(zhǔn)庫(kù)的主要功能有:
1.文本處理,包含文本格式化、正則表達(dá)式匹配、文本差異計(jì)算與合并、Unicode支持,二進(jìn)制數(shù)據(jù)處理等功能
2.文件處理,包含文件操作、創(chuàng)建臨時(shí)文件、文件壓縮與歸檔、操作配置文件等功能
3.操作系統(tǒng)功能,包含線程與進(jìn)程支持、IO復(fù)用、日期與時(shí)間處理、調(diào)用系統(tǒng)函數(shù)、日志(logging)等功能
4.網(wǎng)絡(luò)通信,包含網(wǎng)絡(luò)套接字,SSL加密通信、異步網(wǎng)絡(luò)通信等功能
5.網(wǎng)絡(luò)協(xié)議,支持HTTP,F(xiàn)TP,SMTP,POP,IMAP,NNTP,XMLRPC等多種網(wǎng)絡(luò)協(xié)議,并提供了編寫網(wǎng)絡(luò)服務(wù)器的框架
6.W3C格式支持,包含HTML,SGML,XML的處理。
7.其它功能,包括國(guó)際化支持、數(shù)學(xué)運(yùn)算、HASH、Tkinter等
python利用標(biāo)準(zhǔn)庫(kù)獲取本地IP
這個(gè)最簡(jiǎn)單,但是也最不靠譜,依賴hosts文件,如果hosts文件沒配置,一般容易獲取到127.0.0.1
import socket socket.gethostbyname(socket.gethostname())
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
import socket
alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0])
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
linux上根據(jù)網(wǎng)卡名獲取ip
>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>>
>>> def get_ip(iface = 'eth0'):
... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
... try:
... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
... except:
... return None
... ip = struct.unpack('16sH2x4s8x', res)[2]
... return socket.inet_ntoa(ip)
...
>>> get_ip('eth0')
'10.80.40.234'
>>>
僅限windows
def getIPAddresses():
from ctypes import Structure, windll, sizeof
from ctypes import POINTER, byref
from ctypes import c_ulong, c_uint, c_ubyte, c_char
MAX_ADAPTER_DESCRIPTION_LENGTH = 128
MAX_ADAPTER_NAME_LENGTH = 256
MAX_ADAPTER_ADDRESS_LENGTH = 8
class IP_ADDR_STRING(Structure):
pass
LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
IP_ADDR_STRING._fields_ = [
("next", LP_IP_ADDR_STRING),
("ipAddress", c_char * 16),
("ipMask", c_char * 16),
("context", c_ulong)]
class IP_ADAPTER_INFO (Structure):
pass
LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
IP_ADAPTER_INFO._fields_ = [
("next", LP_IP_ADAPTER_INFO),
("comboIndex", c_ulong),
("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
("addressLength", c_uint),
("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
("index", c_ulong),
("type", c_uint),
("dhcpEnabled", c_uint),
("currentIpAddress", LP_IP_ADDR_STRING),
("ipAddressList", IP_ADDR_STRING),
("gatewayList", IP_ADDR_STRING),
("dhcpServer", IP_ADDR_STRING),
("haveWins", c_uint),
("primaryWinsServer", IP_ADDR_STRING),
("secondaryWinsServer", IP_ADDR_STRING),
("leaseObtained", c_ulong),
("leaseExpires", c_ulong)]
GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
GetAdaptersInfo.restype = c_ulong
GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
adapterList = (IP_ADAPTER_INFO * 10)()
buflen = c_ulong(sizeof(adapterList))
rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
if rc == 0:
for a in adapterList:
adNode = a.ipAddressList
while True:
ipAddr = adNode.ipAddress
if ipAddr:
yield ipAddr
adNode = adNode.next
if not adNode:
break
第三方庫(kù)
https://github.com/ftao/python-ifcfg (本地下載)
import ifcfg import json for name, interface in ifcfg.interfaces().items(): # do something with interface print interface['device'] print interface['inet'] print interface['inet6'] print interface['netmask'] print interface['broadcast'] default = ifcfg.default_interface()
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
windows下安裝python paramiko模塊的代碼
windows下安裝python paramiko模塊,有需要的朋友可以參考下2013-02-02
python opencv將多個(gè)圖放在一個(gè)窗口的實(shí)例詳解
這篇文章主要介紹了python opencv將多個(gè)圖放在一個(gè)窗口,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
python 密碼學(xué)示例——理解哈希(Hash)算法
這篇文章主要介紹了哈希(Hash)算法的相關(guān)資料,幫助大家更好的利用python處理密碼,感興趣的朋友可以了解下2020-09-09
Python實(shí)現(xiàn)簡(jiǎn)易超市管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python如何實(shí)現(xiàn)簡(jiǎn)易超市管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09
Python如何用str.format()批量生成網(wǎng)址(豆瓣讀書為例)
這篇文章主要介紹了Python如何用str.format()批量生成網(wǎng)址(豆瓣讀書為例),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
python GUI庫(kù)圖形界面開發(fā)之PyQt5計(jì)數(shù)器控件QSpinBox詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開發(fā)之PyQt5計(jì)數(shù)器控件QSpinBox詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02
python2.7+selenium2實(shí)現(xiàn)淘寶滑塊自動(dòng)認(rèn)證功能
這篇文章主要為大家詳細(xì)介紹了python2.7+selenium2實(shí)現(xiàn)淘寶滑塊自動(dòng)認(rèn)證功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
python將十六進(jìn)制值轉(zhuǎn)換為字符串的三種方法
這篇文章主要給大家介紹了關(guān)于python將十六進(jìn)制值轉(zhuǎn)換為字符串的三種方法,工作內(nèi)容的需要需求,經(jīng)常需要使用到字符同16進(jìn)制,以及各個(gè)進(jìn)制之間的轉(zhuǎn)換,需要的朋友可以參考下2023-07-07
Python圖片轉(zhuǎn)gif方式(將靜態(tài)圖轉(zhuǎn)化為分塊加載的動(dòng)態(tài)圖)
這篇文章主要介紹了Python圖片轉(zhuǎn)gif方式(將靜態(tài)圖轉(zhuǎn)化為分塊加載的動(dòng)態(tài)圖),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

