SoFunction
Updated on 2024-11-14

Python implementation of the tcp port detection operation example

This article example describes the tcp port detection operation implemented in Python. Shared for your reference, as follows:

# coding=utf-8
import sys
import socket
import re
def check_server(address, port):
  s = ()
  print 'Attempting to connect to %s on port %s' % (address, port)
  try:
    ((address, port))
    print 'Connected to %s on port %s' % (address, port)
    return True
  except  as e:
    print 'Connection to %s on port %s failed: %s' % (address, port, e)
    return False
if __name__ == '__main__':
  from argparse import ArgumentParser
  parser = ArgumentParser(description=u'TCP port detection')
  parser.add_argument(
    '-a',
    '--address',
    dest='address',
    default='localhost',
    help='address for the server')
  parser.add_argument(
    '-p',
    '--port',
    dest="port",
    default=80,
    type=int,
    help='port for the server')
  args = parser.parse_args()
  check = check_server(, )
  print 'check_server returned %s' % check
  (not check)

Test Results.

[hupeng@hupeng-vm Python]$python check_server.py && echo "SUCCESS"
Attempting to connect to localhost on port 80
Connected to localhost on port 80
check_server returned True
SUCCESS
[hupeng@hupeng-vm Python]$python check_server.py -p 81 && echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
[hupeng@hupeng-vm Python]$python check_server.py -p 81 || echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
Failure

Attachment.

in the shell&&cap (a poem)||Methods of use

Return result of the command: true (return 0), false (return non-zero)

command1  && command2: command2 is executed when command1 returns true.

command1  || command2:command2 will not be executed if command1 returns true

More about Python related content can be viewed on this site's topic: thePython Socket Programming Tips Summary》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.