Python獲取本機(jī)IP、mac地址、計(jì)算機(jī)名

在 Python 中獲取 IP地址和在 PHP 中獲取存在一定的獲取差異,但是在 PHP 中更簡(jiǎn)單。那再Python 中怎么獲取呢?

1、Python 獲取本機(jī) MAC地址 :

import uuid
def get_mac_address(): 
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:] 
    return ":".join([mac[e:e+2] for e in range(0,11,2)])

2、Python 獲取 IP地址:

import socket
#獲取本機(jī)電腦名
my_computer_name = socket.getfqdn(socket.gethostname(  ))
#獲取本機(jī)ip
my_ip_addr = socket.gethostbyname(my_computer_name )
print(my_computer_name)
print(my_ip_addr)
結(jié)果為:

PC-20200927HAMT  #電腦名

192.168.2.103 #ip地址

但是注意這里獲取的IP是內(nèi)網(wǎng)IP

3、Linux下 使用下面的方法

import socket
import fcntl
import struct
  
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])
  
>>> get_ip_address('lo')
'127.0.0.1'
  
>>> get_ip_address('eth0')
'11.114.232.121'

親測(cè)有效?。。?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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