[英]How to change IP address of wifi interface using python in linux?
[英]Determine IP address of CONNECTED interface (linux) in python
在我的linux機器上,3個網絡接口中的1個可能實際上已連接到Internet。 我需要獲取當前連接的接口的IP地址,請記住,可能為我的其他2個接口分配了IP地址,只是沒有連接。
我可以通過我的每個界面對網站進行ping操作,以確定哪個具有連接能力,但是與等待ping超時相比,我希望這樣做更快。 而且我不想不必依賴外部網站的建立。
更新:
我所有的接口可能都有ip地址和網關。 這是針對嵌入式設備的。 因此,我們允許用戶在eth0
和eth1
之間進行選擇。 但是,如果用戶告訴我們使用的接口上沒有任何連接,我們可以回過頭來說eth2
(理論上將一直有效)。
因此,我需要做的是首先檢查用戶的選擇是否已連接,如果已連接,則返回該IP。 否則,我需要獲取eth2
的IP。 我可以很好地獲得接口的IP,這只是確定實際連接的接口。
如果系統的默認網關是可靠的,請從route -n
的輸出中獲取,其中包含" UG "
(請注意空格)還將包含網關的IP和活動接口的接口名稱。
解決方案在這里: http : //code.activestate.com/recipes/439093-get-names-of-all-up-network-interfaces-linux-only/
import fcntl
import array
import struct
import socket
import platform
"""
global constants. If you don't like 'em here,
move 'em inside the function definition.
"""
SIOCGIFCONF = 0x8912
MAXBYTES = 8096
def localifs():
"""
Used to get a list of the up interfaces and associated IP addresses
on this machine (linux only).
Returns:
List of interface tuples. Each tuple consists of
(interface name, interface IP)
"""
global SIOCGIFCONF
global MAXBYTES
arch = platform.architecture()[0]
# I really don't know what to call these right now
var1 = -1
var2 = -1
if arch == '32bit':
var1 = 32
var2 = 32
elif arch == '64bit':
var1 = 16
var2 = 40
else:
raise OSError("Unknown architecture: %s" % arch)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * MAXBYTES)
outbytes = struct.unpack('iL', fcntl.ioctl(
sock.fileno(),
SIOCGIFCONF,
struct.pack('iL', MAXBYTES, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
for i in xrange(0, outbytes, var2)]
print localifs()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.