python监听端口

监听tcp协议的端口包

#!/usr/bin/python

import socket

HOST = 'localhost'   # use '' to expose to all networks
PORT = 515

def incoming(host, port):
    """Open specified port and return file-like object"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(0)
    request, addr = sock.accept()
    return request.makefile('r', 0)

for line in incoming(HOST, PORT):
    print line,

监听udp协议的端口包

#!/usr/bin/python

# receive udp packets from all interfaces

import socket

HOST = ''   # use '' to expose to all networks
port = 515

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, port))

try:
    while True:
            data, addr = s.recvfrom(4096)
            back = 'Your address is %r\n' % (addr,)
            print data
except KeyboardInterrupt:
    print()

标签:Linux, Python

评论已关闭