Linux下通过python获取本机ip方法示例

yipeiwu_com6年前Python基础

下面介绍在Linux上利用python获取本机ip的方法.

经过网上调查, 发现大致有两种方法, 一种是调用shell脚本,另一种是利用python中的socket等模块来得到,下面是这两种方法的源码:

#!/usr/bin/env python
#encoding: utf-8
#description: get local ip address
 
import os
import socket, fcntl, struct
 
def 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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python文本相似性计算之编辑距离详解

Python文本相似性计算之编辑距离详解

编辑距离 编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。编辑操作包括将一个字符替换成另一个字符,插入一...

python获取糗百图片代码实例

复制代码 代码如下:from sgmllib import SGMLParserimport urllib2 class sgm(SGMLParser):  &nbs...

python安装pil库方法及代码

python安装pil库方法及代码

安装PIL 在Debian/Ubuntu Linux下直接通过apt安装: $ sudo apt-get install python-imaging Mac和其他版本的Linux...

Python MD5文件生成码

import md5 import sys def sumfile(fobj): m = md5.new() while True: d = fobj.read(8096) if not...

在python中实现调用可执行文件.exe的3种方法

方法一、 os.system() 会保存可执行程序中的打印值和主函数的返回值,且会将执行过程中要打印的内容打印出来 import os main = "project1.exe"...