python 获取本机ip地址的两个方法

yipeiwu_com6年前Python基础

第一种:

复制代码 代码如下:

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')环回地址
#get_ip_address('eth0')主机ip地址


第二种:

复制代码 代码如下:

def get_local_ip(ifname):
import socket, fcntl, struct
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
ret = socket.inet_ntoa(inet[20:24])
return ret
print get_local_ip("eth0")

相关文章

基于pip install django失败时的解决方法

使用pip安装Django时报错,先是: C:\Users\admin>pip install django Collecting django Retrying (Re...

pandas中遍历dataframe的每一个元素的实现

假如有一个需求场景需要遍历一个csv或excel中的每一个元素,判断这个元素是否含有某个关键字 那么可以用python的pandas库来实现。 方法一: pandas的dataframe...

Python导入oracle数据的方法

本文实例讲述了Python导入oracle数据的方法。分享给大家供大家参考。具体如下: import cx_Oracle dns_tns=cx_Oracle.makedsn("1...

Django实现全文检索的方法(支持中文)

PS: 我的检索是在文章模块下 forum/article 第一步:先安装需要的包: pip install django-haystack pip install whoosh p...

python3 反射的四种基本方法解析

这篇文章主要介绍了python3 反射的四种基本方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 class Person(...