refactor network.get_free_port with closing context

This commit is contained in:
Prodesire 2018-02-03 00:28:07 +08:00
parent 7cee0d9267
commit 83864aa9c8
1 changed files with 5 additions and 4 deletions

View File

@ -2,6 +2,8 @@ import socket
import struct
import ctypes
import binascii
from contextlib import closing
from .platform import WINDOWS
from .string import safeencode, safeunicode
from .convert import hex2dec, dec2hex
@ -113,10 +115,9 @@ def is_ipv6(ip):
def get_free_port():
s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
_, port = s.getsockname()
s.close()
with closing(socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)) as s:
s.bind(('127.0.0.1', 0))
_, port = s.getsockname()
return port