首页 > 代码库 > 套接字端口重用

套接字端口重用

用python编写socket程序, 在指定端口上监听服务:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8080
sock.bind((‘‘, port))
sock.listen(1)
print ‘listening on port: %s‘ % port
while True:
    try:
        conn, addr = sock.accept()
        print ‘connected by %s:%s‘ % (addr[0], addr[1])
    except KeyboardInterrupt:
        break
    except socket.error, msg:
        print ‘%s‘ % msg

在端口上提供套接字服务,连接之后终止程序运行,再次运行程序时,程序会出现错误提示:
...
socket.error: [Errno 48] Address already in use

可以通过设置套接字重用选项SO_REUSEADDR来解决上述问题,如:

import socket

port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((‘‘, port))
server.listen(1)
print ‘listening on port: %s‘ % port
while True:
    try:
        conn, addr = server.accept()
        print ‘connected by %s:%s‘ % (addr[0], addr[1])
    except KeyboardInterrupt:
        break
    except socket.error, msg:
        print ‘%s‘ % msg

提示:
import socket

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

state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) # 获取套接字SO_REUSEADDR选项状态
print ‘state state: %s‘ % state

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #设置套接字选项
state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
print ‘state state: %s‘ % state

注: 可以使用telnet命令调试

www.pythonfan.org

套接字端口重用