iphelp.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Windows IP Helper API function wrappers.
  2. # http://msdn2.microsoft.com/en-gb/library/aa366073.aspx
  3. #
  4. # The contents of this file are subject to the Python Software Foundation
  5. # License Version 2.3 (the License). You may not copy or use this file, in
  6. # either source code or executable form, except in compliance with the License.
  7. # You may obtain a copy of the License at http://www.python.org/license.
  8. #
  9. # Software distributed under the License is distributed on an AS IS basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # by Greg Hazel
  15. import ctypes
  16. from ctypes.wintypes import DWORD, ULONG
  17. from BTL.iptypes import inet_addr, IPAddr
  18. Iphlpapi = ctypes.windll.Iphlpapi
  19. class MIB_IPADDRROW(ctypes.Structure):
  20. _fields_ = [("dwAddr", IPAddr),
  21. ("dwIndex", DWORD),
  22. ("dwMask", DWORD),
  23. ("dwBCastAddr", IPAddr),
  24. ("dwReasmSize", DWORD),
  25. ("unused1", ctypes.c_ushort),
  26. ("wType", ctypes.c_ushort),
  27. ]
  28. MAX_INTERFACES = 10
  29. class MIB_IPADDRTABLE(ctypes.Structure):
  30. _fields_ = [("dwNumEntries", DWORD),
  31. ("table", MIB_IPADDRROW * MAX_INTERFACES)]
  32. def get_interface_by_index(index):
  33. table = MIB_IPADDRTABLE()
  34. size = ULONG(ctypes.sizeof(table))
  35. table.dwNumEntries = 0
  36. Iphlpapi.GetIpAddrTable(ctypes.byref(table), ctypes.byref(size), 0)
  37. for n in xrange(table.dwNumEntries):
  38. row = table.table[n]
  39. if row.dwIndex == index:
  40. return str(row.dwAddr)
  41. raise IndexError("interface index out of range")
  42. def get_route_ip(ip=None):
  43. #ip = socket.gethostbyname('bittorrent.com')
  44. # doesn't really matter if this is out of date, we're just trying to find
  45. # the interface to get to the internet.
  46. ip = ip or '38.99.5.27'
  47. ip = inet_addr(ip)
  48. index = ctypes.c_ulong()
  49. Iphlpapi.GetBestInterface(ip, ctypes.byref(index))
  50. index = long(index.value)
  51. try:
  52. interface_ip = get_interface_by_index(index)
  53. except:
  54. interface_ip = None
  55. return interface_ip