欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Linux下通過(guò)python獲取本機(jī)ip方法示例

 更新時(shí)間:2019年09月06日 11:24:45   作者:雪峰流云  
這篇文章主要給大家介紹了關(guān)于在Linux下通過(guò)python獲取本機(jī)ip的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

下面介紹在Linux上利用python獲取本機(jī)ip的方法.

經(jīng)過(guò)網(wǎng)上調(diào)查, 發(fā)現(xiàn)大致有兩種方法, 一種是調(diào)用shell腳本,另一種是利用python中的socket等模塊來(lái)得到,下面是這兩種方法的源碼:

#!/usr/bin/env python
#encoding: utf-8
#description: get local ip address
 
import os
import socket, fcntl, struct
 
def get_ip():
 #注意外圍使用雙引號(hào)而非單引號(hào),并且假設(shè)默認(rèn)是第一個(gè)網(wǎng)卡,特殊環(huán)境請(qǐng)適當(dāng)修改代碼
 out = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()
 print out
 
#另一種方法, 只需要指定網(wǎng)卡接口, 我更傾向于這個(gè)方法
def get_ip2(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])
 
if __name__ == '__main__':
 get_ip()
 print get_ip2('eth0')
 print get_ip2('lo')

下面是運(yùn)行截圖


參考文獻(xiàn)

[1].http://bbs.csdn.net/topics/190130360

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論