python网络编程

太乱了,只把自己写的代码传上来:

 

#basicserver.py

import socket

host = ''
port = 51423

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))

print "Waiting for connections ..."

s.listen(5)

while True:
    clientsock,clientaddr = s.accept()
    print 'Got connection from ',clientsock.getpeername()
    clientsock.close()

 

#broken.py

import sys,socket


result = socket.getaddrinfo(sys.argv[1],None)

counter = 0

for item in result:
    print "%-2d: %s" % (counter,item[4])
    counter += 1

 

#DNSany.py


import sys,DNS

def hierquery(qstring,qtype):
    """Given a query type qtype,returns answers of that type for lookup qstring.
    If not answers are found,removes the most specific component
    (the part before the leftmost period) and retries the query with the
    result. Ic the topmost query fails,returns None."""
    reqobj = DNS.Request()
    try:
        answerobj = reqobj.req(name=qstring,qtype=qtype)
        answers = [x['data'] for x in answerobj.answers if x['type']==qtype]
    except DNS.Base.DNSError:
        answers = []
    if len(answers):
        return  answers
    else:
        remainder = qstring.split(".",1)
        if len(remainder) == 1:
            return None
        else:
            return hierquery(remainder[1],qtype)

def findnameservers(hostname):
    """Attempts to determine the authoritative nameservers for a given
    hostname.Returns None on failure."""
    return hierquery(hostname,DNS.Type.NS)

def getrecordsfromnameserver(qstring,qtype,nslist):
    """Given a list of nameservers in nslist,executes the query requested
    by qstring and qtype on each in order,returning the data from the first server
    that returned 1 or more answers.If no server returned any answers,returns []."""
    for ns in nslist:
        reqobj = DNS.Request(server = ns)
        try:
            answers = reqobj.req(name=qstring,qtype=qtype).answers
            if len(answers):
                return answers
        except DNS.Base.DBSError:
             pass
    return []

def nslookup(qstring,qtype,verbose=1):
    nslist = findnameservers(qstring)
    if nslist == None:
        raise RuntimeError,"Couild not find nameserver to use."
    if verbose:
        print "Using nameservers:",", ".join(nslist)
    return getrecordsfromnameserver(qstring,qtype,nslist)

if __name__ == '__main__':
    query = sys.argv[1]
    DNS.DiscoverNameServers()

    answers = nslookup(query,DNS.Type.ANY)

    if not len(answers):
        print "Not found."
    for item in answers:
        print "%-5s %s" % (item['typename'],item['data'])

 

#DNS-basic.py

import sys,DNS

query = sys.argv[1]
DNS.DiscoverNameServers()

reqobj = DNS.Request()

answerobj = reqobj.req(name=query,qtype=DNS.Type.ANY)

if not len(answerobj.answers):
    print "Not found."
for item in answerobj.answers:
    print "%-5s %s" % (item['typename'],item['data'])

 

#DNSquery.py

import sys,DNS,DNSany,re

def getreverse(query):
    """Given the query,returns an appropriate reverse lookup string
    under IN-ADDR.ARPA if query is an IP address; otherwise,returns None.This
    function is not IPV6-compalite."""
    if re.search('^\d+\.\d+\.\d+\.\d+$',query):
        octets = query.split('.')
        octetc.reverse()
        return '.'.join(octets)+'.IN-ADDR.ARPA'
    return None

def formatline(index,typename,descr,data):
    retval = "%-2s %-5s" % (index,typename)
    data = data.replace("\n","\n ")

    if descr != None and len(descr):
        retval += " %-12s" % (descr + ":")
    return retval + " " + data


DNS.DiscoverNameServers()
queries = [(sys.argv[1],DNS.Type.ANY)]
donequeries = []
descriptions = {'A': 'IP address',
                'TXT': 'Data',
                'PTR': 'Host name',
                'CNAME' : 'Alias for',
                'NS': 'Name Server'}

while len(queries):
    (query,qtype) = queries.pop(0)
    if query in donequeries:
        #Don't look up the same thing twice
        continue
    donequeries.append(query)
    print "-" * 77
    print "Results for %s (lookup type %s)" % (query,DNS.Type.typestr(qtype))

    print
    rev = getreverse(query)

    if rev:
        print "IP address given; doing reverse lookup using ",rev
        query = rev
    answers = DNSany.nslookup(query,qtype,verbose=0)
    if not len(answers):
        print "Not fonund."

    count = 0
    for answer in answers:
        count += 1
        if answer['typename'] == 'MX':
            print formatline(count,answer['typename'],'Mail server',
                             "%s priority %d" % (answer['data'][1],
                                                 answer['data'][0]))
            queries.append((answer['data'][1],DNS.Type.A))
        elif answer['typename'] == 'SOA':
            data = "\n" + "\n".join([str(x) for x in answer['data']])
            print formatline(count,"SOA","Start of authority",data)
        elif answer['typename'] in descriptions:
            print formatline(count,answer['typename'],descriptions[answer['typename']],answer['data'])
        else:
            print formatline(count,answer['typename'],None,str(answer['data']))

        if answer['typename'] in ['CNAME','PTR']:
            queries.append((answer['data'],DNS.Type.ANY))
        if answer['typename'] == 'NS':
            queries.append((answer['data'],DNS.Type.A))

 

#echoclient.py

import socket,sys
port = 51432
host = 'localhost'

data = "x" * 10485760

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))

byteswritten = 0

while byteswritten < len(data):
    startpos = byteswritten
    endpos = min(byteswritten+1024,len(data))
    byteswritten += s.send(data[startpos:endpos])
    sys.stdout.write("Wrote %d bytes\r" % byteswritten)
    sys.stdout.flush()

s.shutdown(1)

print "All data sent."

while True:
    buf = s.recv(1024)
    if not len(buf):
        break
    sys.stdout.write(buf)

 

#echoserver.py

import socket,traceback

host = ''
port = 51432

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)

while True:
    try:
        clientsock,clientaddr = s.accept()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
        continue

    try:
        print "Got connection from",clientsock.getpeername()
        while  True:
            data = clientsock.recv(4096)
            if not len(data):
                break
            clientsock.sendall(data)
    except (KeyboardInterrupt,SystemExit):
        raise
    except:
        traceback.print_exc()

    try:
        clientsock.close()
    except KeyboradInterrupt:
        raise
    except:
        traceback.print_exc()

 

#environment.py

import sys,socket

def getipaddrs(hostname):
    """Given a hos tname,perform a standard (forward) lookup and
        return a list of IP addresses for that host."""
    result = socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM)
    return [x[4][0] for x in result]


hostname = socket.gethostname()
print "Host name: " ,hostname

print "Fully-qualified name:",socket.getfqdn(hostname)

try:
    print "IP address:",", ".join(getipaddrs(hostname))
except socket.gaierror,e:
    print "Couldn't not get IP addresses:",e

 

#errorserver.py

import socket,traceback


host = ''
port = 51423

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)

print "Waiting client connections ... "

while True:
    try:
        clientsock,clientaddr = s.accept()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
        continue

    try:
        print "Got connection from",clientsock.getpeername()
    except (KeyboardInterrupt,SystemExit):
        raise
    except:
        traceback.print_exc()

    try:
        clientsock.close()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
    

 

#getaddrinfo-basic.py

import sys,socket

result = socket.getaddrinfo(sys.argv[1],None)
print result[0][4]

 

 

#getaddrinfo-list

import sys,socket

result = socket.getaddrinfo(sys.argv[1],None,0,socket.SOCK_STREAM)



counter = 0

for item in result:
    print "%-2d: %s" % (counter,item[4])
    counter += 1
    

 

#gethostbyaddr-basic.py

import sys,socket

try:
    result = socket.gethostbyaddr(sys.argv[1])

    print 'Primary hostname: '
    print " " + result[0]

    print "\nAdresses:"
    for item in result[2]:
        print " " + item

except socket.herror,e:
    print "Couldn't look up name:",e

 

#gethostbyaddr-paranoid.py

import sys,socket

def getipaddrs(hostname):
    """Get a list of IP addresses from a given hostname.This is a standard
        (forward) lookup."""
    result = socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM)
    return [x[4][0] for x in result]

def gethostname(ipaddr):
    """Get the hostname from a given IP address. This is a reverse
        lookup."""
    return socket.gethostbyaddr(ipaddr)[0]

try:
    hostname = gethostname(sys.argv[1])

    ipaddrs = getipaddrs(hostname)
except socket.herror,e:
    print "No host names available for %s; this may be normal." % sys.argv[1]
    sys.exit(0)

except socket.gaierror,e:
    print "Got hostname %s,but it could not be forward-resolved: %s" %(hostname,str(e))
    sys.exit(1)


if not sys.argv[1] in ipaddrs:
    print "Got hostname %s,but on forward lookup," % hostname
    print "original IP %s did not appear in IP address list." % sys.argv[1]
    sys.exit(1)

print 'Validated hostname:',hostname

 

#getinformation.py

import socket

print 'Creating socket....',
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print 'done.'

print 'Looking up port number ...',
port = socket.getservbyname('http','tcp')
print 'done.'

print 'Connecting to remote host on port %d...' % port
s.connect(('www.google.com',port))
print 'done.'


print 'Conencted from',s.getsockname()
print 'connected to',s.getpeername()            

 

#getport.py
import socket

print 'Creating socket...',
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print 'done.'

print 'Looking up port number...',
port = socket.getservbyname('http','tcp')
print 'done.'

print 'Connecting to remote host on %d...' % port,
s.connect(('www.google.com',port))
print 'done.'

 

#htmlparse.py

from urllib import urlopen
from HTMLParser import HTMLParser

class Scraper(HTMLParser):
    in_h3 = False
    in_link = False

    def handle_starttag(self,tag,attrs):
        attrs = dict(attrs)
        if tag == 'h3':
            self.in_h3 = True
        if tag == 'a' and 'href' in attrs:
            self.in_link = True
            self.chunks = []
            self.url = attrs['href']

    def handle_data(self,data):
        if self.in_link:
            self.chunks.append(data)

    def handle_endtag(self,tag):
        if tag == 'h3':
            self.in_h3 = False
        if tag == 'a':
            if self.in_h3 and self.in_link:
                print '%s (%s)' % (''.join(self.chunks),self.url)
            self.in_link = False

#text = urlopen('http://bbs.gameres.com/forum_101_1.html').read()
text = urlopen('http://www.baidu.com')
parser = Scraper()
parser.feed(text)
parser.close()

 

 

#inetdserver.py

import sys
print "Welcom"
print "Please enter a string: "

sys.stdout.flush()
line = sys.stdin.readline().strip()

print "You entered %d characters." % len(line)

 

#inetdsocket.py

import sys,socket,time

s = socket.fromfd(sys.stdin.fileno(),socket.AF_INET,socket.SOCK_STREAM)
s.sendall("Welcome .\n")
s.sendall("According to our records,you are connected from %s.\n" % str(s.getpeername()))
s.sendall("The local time is %s.\n" % time.asctime())

 

#inetdudpserver.py

import socket,time,sys

s = socket.fromfd(sys.stdin.fileno(),socket.AF_INET,socket.SOCK_DGRAM)
message,address = s.recvfrom(8192)

s.connect(address)

for i in range(10):
    s.send("Reply %d : %s" % (i+1,message))
    time.sleep(2)

s.send("OK,I'm done sending replies.\n")

 

#inetdwaitserver.py

import socket,time,sys,os
s = socket.fromfd(sys.stdin.fileno(),socket.AF_IENT,socket.SOCK_DGRAM)
message,address = s.recvfrom(8192)

localaddr = s.getsockname()
s.close()

pid = os.fork()

if pid:
    sys.exit(0)

s2 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s2.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR)
s2.bind(localaddr)
s2.connect(address)


for i in range(10):
    s2.send("Reply %d: %s" % (i+1,message))
    time.sleep(2)
s2.send("OK,I'm done sending replies.\n")

 

#screenraw.py

from urllib import urlopen
import re


#p = re.compile('.*<h2><a class=.*?> herf="(.*?)">(.*?)</a>.*')
p = re.compile('http.*url.*')
text = urlopen('http://www.baidu.com').read()

#for url in p.findall(text):
 #   print '%s ' % url
import pprint
pprint.pprint(p.findall(text))

 

import socket

host = ''
port = 51423

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)

print "Server is running on port %d; press Ctr-c to terinate." % port


while True:
    clientsock,clientaddr = s.accept()
    clientfile = clientsock.makefile('rw',0)
    clientfile.write("Welcom, " + str(clientaddr) + "\n")
    clientfile.write("Please enter a string: ")
    line = clientfile.readline().strip()
    clientfile.write("You entered %d characters.\n" % len(line))
    clientfile.close()
    clientsock.close()

 

#shutdown.py

import socket,sys,time

host = sys.argv[1]
textport = sys.argv[2]
filename = sys.argv[3]

try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
    print 'Strange error creating socket: %s' % e
    sys.exit(1)


try:
    port = int(textport)
except ValueError:
    try:
        port = socket.getservbyname(textport,'tcp')
    except socket.error,e:
        print  "Couldn't find port: %s" % e
        sys.exit(1)

try:
    s.connect((host,port))
except socket.gaierror,e:
    print 'Address-related error connecting to server: %s' % e
    sys.exit(1)
except socket.error,e:
    print 'Connetion error : %s' % e
    sys.exit(1)


print 'sleeping ...'
time.sleep(10)
print 'Continuing.'

try:
    s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error,e:
    print 'Error sending data: %s' % e
    sys.exit(1)

try:
    s.shutdown(1)
except socket.error,e:
    print "Error sending data (detected by shutdown): %s" % e
    sys.exit(1)
    
while True:
    try:
        buf = s.recv(2048)
    except socket.error,e:
        print 'Error receiving data: %s' % e
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)

 

#shutdownfile.py

import socket,sys,time

host = sys.argv[1]
textport = sys.argv[2]
filename = sys.argv[3]

try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
    print "Strang eror creating socket: %s" % e
    sys.exit(1)


try:
    s.connect((host,port))
except socket.gaierror,e:
    print "Address-related error connecting to server: %s" % e
    sys.exit(1)
except socket.error,e:
    print "Connection error: %s" % e
    sys.exit(1)


fd = s.makefile('rw',0)

print "sleeping ..."
time.sleep(10)
print "Continuing."


try:
    fd.write("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error,e:
    print "Error sending data: %s" % e
    sys.exit(1)

try:
    fd.flush()
except socket.error,e:
    print "Error sending data (detected by flush) : %s" % e
    sys.exit(1)

try:
    s.shutdown(1)
    s.close()
except socket.error,e:
    print "Error sending data (dectected by shutdown) : %s" % e
    sys.exit(1)

while True:
    try:
        buf = fd.read(2048)
    except socket.error,e:
        print "Error receiving data: %s" % e
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)

 

#socket1.py

import socket

print 'Creating socket ...',

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

print 'done ...'

print 'Connecting to remote host ...',

s.connect(("www.google.com",80))

print 'Done ...'

 

#socketrrors.py
import socket,sys


textport = 80
filename = r'E:/project.txt'


try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
    print 'Strange error creating socket: %s' % e
    sys.exit(1)


try:
    port = int(textport)
except ValueError:
    try:
        port = socket.getservbyname(textport,'tcp')
    except socket.error,e:
        print "Couldn't find your port: %s" % e
        sys.exit(1)
host = 'www.baidu.com'

try:
    s.connect((host,port))
except socket.gaierror,e:
    print 'Address-related error connecting to server: %s' % e
    sys.exit(1)
except socket.error,e:
    print 'Connection error: %s' % e
    sys.exit(1)


try:
    s.sendall('GET %s HTTP/1.0\r\n\r\n' % filename)
except socket.error,e:
    print 'Error sending data: %s' % e
    sys.exit(1)


while True:
    try:
        buf = s.recv(2048)
    except socket.error,e:
        print 'Error receiving data: %s' % e
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)
    

 

#sockeksever.py

import socket
import sys
from thread import *

HOST = ''    # Symbolic name meaning all available interfaces
PORT = 8889    # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
    
print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
    
    #infinite loop so that function do not terminate and thread do not end.
    while True:
        
        #Receiving from client
        data = conn.recv(1024)
        reply = 'OK...' + data
        if not data: 
            break
    
        conn.sendall(reply)
    
    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()
s.close()

 

#sockettest.py

#Socket client example in python

import socket    #for sockets
import sys    #for exit

#create an INET, STREAMing socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()
    
print 'Socket Created'

host = 'oschina.net';
port = 80;

try:
    remote_ip = socket.gethostbyname( host )

except socket.gaierror:
    #could not resolve
    print 'Hostname could not be resolved. Exiting'
    sys.exit()

#Connect to remote server
s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
message = "GET / HTTP/1.1\r\nHost: oschina.net\r\n\r\n"

try :
    #Set the whole string
    s.sendall(message)
except socket.error:
    #Send failed
    print 'Send failed'
    sys.exit()

print 'Message send successfully'

#Now receive data
reply = s.recv(4096)

print reply

s.close()

 

#syslogsample.py

import syslog,sys,StringIO,traceback,os

def logexception(includetraceback = 0):
    exctype,exception,exctraceback = sys.exc_info()
    excclass = str(exception.__class___)
    message = str(exception)

    if not includetraceback:
        syslog.syslog(syslog.LOG_ERR,"%s: %s" % (excclass,message))
    else:
        excfd = StringIO.StringIO()
        traceback.print_exception(exctype,exception,exctraceback,None,excfd)

        for line in excfd.getvalue().split("\n"):
            syslog.syslog(syslog.LOG_ERR,line)


def initsyslog():
    syslog.openlog("%s[%d]" % (os.path.basename(sys.argv[0]),os.getpid()),0,syslog.LOG_DAEMON)
    syslog.syslog("Started.")


initsyslog()

try:
    raise RuntimeError,"Exception 1"
except:
    logexception(0)

try:
    raise RuntimeError,"Exception 2"
except:
    logexception(1)

syslog.syslog("I'm terminating.")

 

#udp.py

import socket,sys

host = sys.argv[1]
textport = sys.argv[2]

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

try:
    port = int(textport)
except ValueError:
    port = socket.getservbyname(textport,"udp")

s.connect((host,port))
print "Enter data to transmit: "
data = sys.stdin.readline().strip()
s.sendall(data)

print "Looking for replies ; press  Ctrl-C or Ctrl-Break to stop."

while True:
    buf = s.recv(2048)
    if not len(buf):
        break;
    sys.stdout.write(buf)

 

#udpechoserver.py

import socket,traceback

host = ''
port = 51423

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))


while True:
    try:
        message,address = s.recvfrom(8192)33
        print "Got data from",address
        s.sendto(message,address)

    except (KeyboardInterrupt,SystemExit):
        raise
    except:
        traceback.print_exc()

    

 

#udptimeserver.py

import socket,traceback,time,struct

host = ''
port = 51423

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))

while True:
    try:
        message,address = s.recvfrom(8192)
        print "Got from client :",address
        secs = int(time.time())
        secs -= 60*60*24
        secs += 2208988800
        reply = struct.pack("!I",secs)
        s.sendto(reply,address)
    except (KeyboardInterrupt,SystemExit):
        raise
    except:
        traceback.print_exc()

 

 

#udptime.py

import socket,sys,struct,time


port = 51423

host = socket.gethostname()

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.sendto('',(host,port))

print "Looking for replies ; press Ctrl-C to stop."

buf = s.recvfrom(2048)[0]

if len(buf) != 4:
    print "Wrong-sized reply %d: %s" % (len(buf),buf)
    sys.exit(1)

secs = struct.unpack("!I",buf)[0]
secs -= 2208988800

print time.ctime(int(secs))

 

这些比较乱,只看代码,属于网络编程的基础部分

 

 

 

 

 

 

posted @ 2013-08-30 17:38  lfsblack  阅读(1086)  评论(0编辑  收藏  举报