Python獲取本機(jī)網(wǎng)卡的MAC地址、IP地址和路由表

一、獲取Mac地址

1、單個網(wǎng)卡

>>> import uuid
>>> address = hex(uuid.getnode())[2:]
>>> '-'.join(address[i:i+2] for i in range(0, len(address), 2))
'f0-03-8c-09-8c-34'

2、獲取多網(wǎng)卡MAC地址

使用pip安裝Python擴(kuò)展庫psutil,運(yùn)行以下的代碼:

from psutil import net_if_addrs

for k, v in net_if_addrs().items():
    for item in v:
        address = item[1]
        if '-' in address and len(address)==17:
            print(address)

二、獲取本機(jī)IP地址

1、windows下:
Python標(biāo)準(zhǔn)庫socket中有可以獲取本機(jī)IPV4地址的方法,下面是網(wǎng)上非常常見的一種用法:

>>> import socket
>>> hostname = socket.gethostname()
>>> hostname
'DESKTOP-I734J3O'
>>> socket.gethostbyname(hostname)
'192.168.0.103'

2、Mac下:上面的代碼在Windows下運(yùn)行良好,但是無意中發(fā)現(xiàn)在Mac系統(tǒng)下運(yùn)行不正常,返回的是本機(jī)回環(huán)地址127.0.0.1,而不是真正的IP地址。經(jīng)過查閱大量資料,終于發(fā)現(xiàn)socket模塊中另一個函數(shù)的妙用,那就是getaddrinfo()函數(shù),該函數(shù)用法為getaddrinfo(host, port, family=0, type=0, proto=0, flags=0),返回值是一個五元組的列表,該五元組形式為(family, type, proto, canonname, sockaddr),其中最后一個元素sockaddr對于IPV4協(xié)議是(IP address, port)形式的元組,而對于IPV6協(xié)議是(address, port, flow info, scope id)形式的元組,也就是說,不管是IPV4還是IPV6,上面的函數(shù)都可以正確地獲取IP地址。
于是,繼續(xù)上面的代碼:

>>> addrs = socket.getaddrinfo(hostname,None)
>>> for item in addrs:
     print(item)
 
(, 0, 0, '', ('fe80::b976:b065:27d:3747%10', 0, 0, 10))
(, 0, 0, '', ('fe80::1456:951:2418:27cf%7', 0, 0, 7))
(, 0, 0, '', ('192.168.0.103', 0))
(, 0, 0, '', ('2001:0:9d38:6ab8:1456:951:2418:27cf', 0, 0, 0))

如此便可以獲取本機(jī)所有IPV4和IPV6地址,如果只想獲取IPV4地址,再繼續(xù)執(zhí)行下面的代碼:

>>> [item[4][0] for item in addrs if ':' not in item[4][0]][0]
'192.168.0.103'

三、路由表

方法:采用ARP協(xié)議獲取局域網(wǎng)內(nèi)所有計(jì)算機(jī)的IP地址與MAC地址,思路是使用系統(tǒng)命令arp獲取ARP表并生成文本文件,然后從文件中讀取和解析信息。

import os
from socket import gethostbyname, gethostname
獲取本機(jī)IP地址
host = gethostbyname(gethostname())
獲取ARP表
os.system('arp -a > temp.txt')

with open('temp.txt') as fp:
    for line in fp:
        line = line.split()[:2]
        if line and\
           line[0].startswith(host[:4]) and\
           (not line[0].endswith('255')):
            print(':'.join(line))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容