Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple TCP connect test script
#!/usr/bin/env python
import socket
import sys
import time
def run():
host = sys.argv[1]
port = int(sys.argv[2])
iteration = 0
failed = 0
results = []
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.0)
start_time = time.time()
try:
sock.connect((host, port))
end_time = time.time()
diff_time = (end_time - start_time) * 1000
except socket.timeout:
print " - CONNECT to %s:%s (#%s) timed out" % (host, port, iteration)
failed += 1
continue
finally:
sock.close()
iteration += 1
print " - CONNECT to %s:%s (#%s) took %.1f ms" % (host, port, iteration, diff_time)
results.append(diff_time)
time.sleep(0.1)
except KeyboardInterrupt:
print ""
print ("%s CONNECTs (%s failed) %.1f%% success rate to %s:%s. min/avg/max = "
"%.1f/%.1f/%.1f ms") % (
iteration, failed, (float(iteration - failed) / iteration * 100), host, port,
min(results), (float(sum(results)) / float(len(results))),
max(results))
break
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment