在Linux上利用python获取本机ip
生活随笔
收集整理的這篇文章主要介紹了
在Linux上利用python获取本机ip
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面介紹在Linux上利用python獲取本機ip的方法.
經過網上調查, 發現大致有兩種方法, 一種是調用shell腳本,另一種是利用python中的socket等模塊來得到,下面是這兩種方法的源碼:
#!/usr/bin/env python
#encoding: utf-8
#description: get local ip addressimport os
import socket, fcntl, structdef get_ip():#注意外圍使用雙引號而非單引號,并且假設默認是第一個網卡,特殊環境請適當修改代碼out = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()print out#另一種方法, 只需要指定網卡接口, 我更傾向于這個方法
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')下面是運行截圖
參考文獻
[1].http://bbs.csdn.net/topics/190130360
總結
以上是生活随笔為你收集整理的在Linux上利用python获取本机ip的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Ubuntu 14.04 64bit上
- 下一篇: 在CentOS 6.6 64bit上安装