用python获取本机IP地址[in
Linux]
方法一:【最好的一个,<推荐>】
可以不必知道使用的是哪个网络设备,十分方便的获得正在使用的IP地址!
#!/usr/bin/env python
import socket
def get_my_ip():
"""
Returns
the actual ip of the local machine.
This
code figures out what source address would be used if some
traffic
were to
be sent out to some well known address on the Internet. In
this
case, a
Google DNS server is used, but the specific address does
not
matter
much. No traffic is actually
sent.
"""
try:
csock =
socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
csock.connect(('8.8.8.8',
80))
(addr, port) =
csock.getsockname()
csock.close()
return
addr
except
socket.error:
return
"127.0.0.1"
if __name__ ==
"__main__":
print
get_my_ip()
方法二:【最灵活的一个】
需要指明此时正在使用的网络设备名!
#!/usr/bin/env 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])
Local_ip=get_ip_address("xxx")#xxx表示网络设备名
阅读(5521) | 评论(0) | 转发(0) |