# HG changeset patch # User Thierry Florac # Date 1541760914 -3600 # Node ID b9398ca282c75115c872c35f9521fcda7f1b199f # Parent 8567cd9648961dc4e665e3c0bd489fe65cd217cb Added function to check if TCP port is available diff -r 8567cd964896 -r b9398ca282c7 src/pyams_utils/protocol/tcp.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/pyams_utils/protocol/tcp.py Fri Nov 09 11:55:14 2018 +0100 @@ -0,0 +1,21 @@ +# +# Copyright (c) 2008-2018 Thierry Florac +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# + +__docformat__ = 'restructuredtext' + +import socket + + +def is_port_in_use(port, hostname='localhost'): + """Check if given port is already used locally""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex((hostname, port)) == 0