testupnpigd.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #! /usr/bin/python
  2. # $Id: testupnpigd.py,v 1.4 2008/10/11 10:27:20 nanard Exp $
  3. # MiniUPnP project
  4. # Author : Thomas Bernard
  5. # This Sample code is public domain.
  6. # website : http://miniupnp.tuxfamily.org/
  7. # import the python miniupnpc module
  8. import miniupnpc
  9. import socket
  10. import BaseHTTPServer
  11. # function definition
  12. def list_redirections():
  13. i = 0
  14. while True:
  15. p = u.getgenericportmapping(i)
  16. if p==None:
  17. break
  18. print i, p
  19. i = i + 1
  20. #define the handler class for HTTP connections
  21. class handler_class(BaseHTTPServer.BaseHTTPRequestHandler):
  22. def do_GET(self):
  23. self.send_response(200)
  24. self.end_headers()
  25. self.wfile.write("OK MON GARS")
  26. # create the object
  27. u = miniupnpc.UPnP()
  28. #print 'inital(default) values :'
  29. #print ' discoverdelay', u.discoverdelay
  30. #print ' lanaddr', u.lanaddr
  31. #print ' multicastif', u.multicastif
  32. #print ' minissdpdsocket', u.minissdpdsocket
  33. u.discoverdelay = 200;
  34. try:
  35. print 'Discovering... delay=%ums' % u.discoverdelay
  36. ndevices = u.discover()
  37. print ndevices, 'device(s) detected'
  38. # select an igd
  39. u.selectigd()
  40. # display information about the IGD and the internet connection
  41. print 'local ip address :', u.lanaddr
  42. externalipaddress = u.externalipaddress()
  43. print 'external ip address :', externalipaddress
  44. print u.statusinfo(), u.connectiontype()
  45. #instanciate a HTTPd object. The port is assigned by the system.
  46. httpd = BaseHTTPServer.HTTPServer((u.lanaddr, 0), handler_class)
  47. eport = httpd.server_port
  48. # find a free port for the redirection
  49. r = u.getspecificportmapping(eport, 'TCP')
  50. while r != None and eport < 65536:
  51. eport = eport + 1
  52. r = u.getspecificportmapping(eport, 'TCP')
  53. print 'trying to redirect %s port %u TCP => %s port %u TCP' % (externalipaddress, eport, u.lanaddr, httpd.server_port)
  54. b = u.addportmapping(eport, 'TCP', u.lanaddr, httpd.server_port,
  55. 'UPnP IGD Tester port %u' % eport, '')
  56. if b:
  57. print 'Success. Now waiting for some HTTP request on http://%s:%u' % (externalipaddress ,eport)
  58. try:
  59. httpd.handle_request()
  60. httpd.server_close()
  61. except KeyboardInterrupt, details:
  62. print "CTRL-C exception!", details
  63. b = u.deleteportmapping(eport, 'TCP')
  64. if b:
  65. print 'Successfully deleted port mapping'
  66. else:
  67. print 'Failed to remove port mapping'
  68. else:
  69. print 'Failed'
  70. httpd.server_close()
  71. except Exception, e:
  72. print 'Exception :', e