python獲取網卡IP地址

 

  1. #!/usr/bin/env python 
  2. # -*- coding: utf-8 -*- 
  3.  
  4. import socket 
  5. import fcntl 
  6. import struct 
  7.  
  8. def get_ip_address(ifname): 
  9.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
  10.     return socket.inet_ntoa(fcntl.ioctl( 
  11.         s.fileno(), 
  12.         0x8915,  # SIOCGIFADDR 
  13.         struct.pack('256s', ifname[:15]) 
  14.     )[20:24]) 
  15.  
  16. print "eth0 = "+ get_ip_address('eth0'
  17. print "lo = " + get_ip_address('lo'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章