的解決方案是在這裏: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()
什麼分類的界面爲 「下」?它沒有網關嗎?它有一個網關,但網關將無法訪問? – 2010-10-07 19:35:07
只有通過查看IP才能確定路由。作爲一個例子,不止一個接口可以路由到互聯網(認爲有線和無線)。它們中的任何一個都可以(直接)路由到互聯網,但可能在處理某些流量的路徑中有代理。 – Joe 2010-10-07 19:35:21
除非您使用ICMP,TCP/IP,UDP等與互聯網中的某個服務器建立連接,否則沒有任何連接到Internet的事情。除非您與某個服務通話並收到回覆,否則不能說您已連接否則到互聯網。 – 2010-10-07 19:59:42