简体   繁体   English

Python 3.4和Netifaces-获取一个特定的IPv4地址

[英]Python 3.4 & Netifaces - Get one specific IPv4 address

I am trying to get (or return) an IP address from my mobile internet interface, which changes everytime I replug it into my laptop. 我试图从移动互联网接口获取(或返回)IP地址,每次将其重新插入笔记本电脑时,该地址都会更改。 I have found the interface using netiface: 我发现使用netiface的界面:

import netiface

netifaces.interfaces()

Which gave me bunch of interfaces, and say that the interface I need is xxx123-yyy456, so I do the following: 这给了我很多接口,并说我需要的接口是xxx123-yyy456,所以我执行以下操作:

myIface = netifaces.ifaddressess('xxx123-yyy456')
myIface[netifaces.AF_INET]

Which shows me these addresses (numbers changed): 其中显示了这些地址(数字已更改):

[{'addr': '10.0.0.1', 'broadcast': '10.0.0.2', 'netmask': '255.255.255.255'}]

Which I'm not sure if it is a list or dictionary, thus I'm struggling with getting the ip address out of it. 我不确定是列表还是字典,因此我在努力获取IP地址。 I've got only as far as getting a list of three words: 我只得到三个词的清单:

addr
broadcast
netmask

What I need is the address number after 'addr':, so I can work with it and call for it later on. 我需要的是'addr':之后的地址,因此我可以使用它并稍后再调用。 For example like: 例如:

myIp = <the IP the interface curently has>
print(myIp)

So that everytime I replug my mobile internet interface I would each time get the new address. 这样,每次我重新插入移动互联网接口时,我都会得到新地址。

You have a list, containing one element, a dictionary. 您有一个包含一个元素的列表,一个字典。 The square brackets denote a list, and the curly denote the dictionary within. 方括号表示列表,而大括号表示其中的字典。

>>> results = [{'addr': '10.0.0.1', 'broadcast': '10.0.0.2', 'netmask': '255.255.255.255'}]
>>> results[0]
{'addr': '10.0.0.1', 'broadcast': '10.0.0.2', 'netmask': '255.255.255.255'}
>>> results[0]['addr']
'10.0.0.1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM