python之迷你版Httpd服务器

## miniHttpd.py

import os, sys, platform
import posixpath
import BaseHTTPServer
from SocketServer import ThreadingMixIn
import threading
import urllib, urllib2
import cgi
import shutil
import mimetypes
import re
import time


__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "bones7456"
__home_page__ = ""

try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO
    
def get_ip_address(ifname):
  import socket
  import fcntl
  import struct
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[20:24]) # SIOCGIFADDR

class GetWanIp:
  def getip(self):
    try:
      myip = self.visit("http://ip.taobao.com/service/getIpInfo.php?ip=myip")
    except:
      print "ip.taobao.com is Error"
      try:
        myip = self.visit("http://www.bliao.com/ip.phtml")
      except:
        print "bliao.com is Error"
        try:
          myip = self.visit("http://www.whereismyip.com/")
        except: # 'NoneType' object has no attribute 'group'
          print "whereismyip is Error"
          myip = "127.0.0.1"
    return myip
  def visit(self,url):
    opener = urllib2.urlopen(url, None, 3)
    if url == opener.geturl():
      str = opener.read()
    return re.search('(\d+\.){3}\d+',str).group(0)
  
def showTips():
  print ""
  print '----------------------------------------------------------------------->> '
  try: 
    port = int(sys.argv[1])
  except Exception, e:
    print '-------->> Warning: Port is not given, will use deafult port: 8080 '
    print '-------->> if you want to use other port, please execute: '
    print '-------->> python SimpleHTTPServerWithUpload.py port '
    print "-------->> port is a integer and it's range: 1024 < port < 65535 "
    port = 8080
    
  if not 1024 < port < 65535: port = 8080
  # serveraddr = ('', port)
  print '-------->> Now, listening at port ' + str(port) + ' ...'
  osType = platform.system()
  if osType == "Linux":
    print '-------->> You can visit the URL:   http://'+ GetWanIp().getip() + ':' +str(port)
  else:
    print '-------->> You can visit the URL:   http://127.0.0.1:' +str(port)
  print '----------------------------------------------------------------------->> '
  print ""
  return ('', port)
  
serveraddr = showTips()  
  
def sizeof_fmt(num):
  for x in ['bytes','KB','MB','GB']:
    if num < 1024.0:
      return "%3.1f%s" % (num, x)
    num /= 1024.0
  return "%3.1f%s" % (num, 'TB')
  
def modification_
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值