在linux 或是 windows,只要下個 ifconfig, ipconfig 就可以取得目前IP位置了,那用程式又該如何取得呢?
能取得ip的方式也很多種,這裡介紹使用socket來取得目前主機ip
第一種方式取得system上的ip
import os
import socket
""" 判斷是否為linux system """
if os.name != 'nt':
import fcntl
import struct
""" 取得裝至上的訊息 """
def get_interface_ip(ifname):
get_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(get_s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith('127.') and os.name != 'nt':
interfaces = ["eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0",]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
第二種,進行對外連線來取得當前網卡的ip
import socket
def getIP():
myname = socket.getfqdn(socket.gethostname())
get_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
get_s.connect(('8.8.8.8', 0))
ip = ('hostname: %s, localIP: %s') % (myname, get_s.getsockname()[0])
return ip