Use Python to find nine consecutive idle ports

Source: Internet
Author: User
This article mainly introduces how to find nine consecutive idle ports in Python. For more information, see this article. it mainly introduces how to find nine consecutive idle ports in Python, for more information, see

I. project requirements

To install a software, enter the idle port during configuration. Check whether a port of five platforms is occupied

Five platforms are windows, linux, aix, hp, and solaris.

2. there are two implementation schemes

1. use


def isInuse(ipList, port):  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  flag=True  for ip in ipList:    try:      s.connect((ip, int(port)))      s.shutdown(2)      print '%d is inuse' % port      flag=True      break    except:      print '%d is free' % port      flag=False  return flag


In the try module, if s. connect (ip, int (port) succeeds, the port is occupied.

Otherwise, the connect operation fails and it will enter the memory T, indicating that the port is not occupied.

However, in addition to 127.0.0.1 and 0.0.0.0, the ip address of the port listener may also be the ip address of the local Lan, such as 222.25.136.17, or the ip address of the machine that communicates with the port.

You can use this method to obtain the LAN ip address.


def getLocalIp():  localIP = socket.gethostbyname(socket.gethostname())  return localIP


This code only performs connect for ipList = ("127.0.0.1", "0.0.0.0", getLocalIp ()


import sysimport osimport socketdef isInuse(ipList, port):  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  flag=True  for ip in ipList:    try:      s.connect((ip, int(port)))      s.shutdown(2)      print '%d is inuse' % port      flag=True      break    except:      print '%d is free' % port      flag=False  return flagdef getLocalIp():  localIP = socket.gethostbyname(socket.gethostname())  return localIPdef checkNinePort(startPort):  flag = True  ipList = ("127.0.0.1","0.0.0.0",getLocalIp())  for i in range(1, 10):    if (isInuse(ipList, startPort)):      flag = False      break    else:      startPort = startPort + 1  return flag, startPortdef findPort(startPort):  while True:    flag, endPort = checkNinePort(startPort)    if (flag == True): #ninePort is ok      break    else:      startPort = endPort + 1  return startPortdef main():  startPort=51988  # startPort = int(sys.argv[1])  print findPort(startPort)main()


2. use netstat output information to find Port number matching

The accuracy of the first method depends on the ip address in connect (ip, int (port). What kind of ip address set is complete? are you sure this port is not occupied?

So there is the following method:

** In linux, you can use netstat-tnpl to obtain port listening information,

Observe tcp 0 0 10.173.1.208: 3210 0.0.0.0: * LISTEN 55563/repserver

Port 10.173.1.208: 3210 is occupied.

Search for this information: 5000. If yes, port 5000 is LISTEN **.

If the output result does not contain a 5000 character, the port is not occupied.


netstat - tnpl | grep 321tcp 0 0 10.173.1.208:3211 0.0.0.0:* LISTEN 55563/***tcp 0 0 0.0.0.0:3212 0.0.0.0:* LISTEN 55586/***tcp 0 0 10.173.1.208:3213 0.0.0.0:* LISTEN 55707/***tcp 0 0 0.0.0.0:3214 0.0.0.0:* LISTEN 54272/javatcp 0 0 0.0.0.0:3215 0.0.0.0:* LISTEN 54272/javatcp 0 0 10.173.1.208:3216 0.0.0.0:* LISTEN 54822/***tcp 0 0 10.173.1.208:3217 0.0.0.0:* LISTEN 34959/***tcp 0 0 10.173.1.208:3218 0.0.0.0:* LISTEN 54849/***


Provide the code based on this idea.

The methods for viewing port information on AIX, HP, WINDOWS, LINUX, and SOLARIS are different,

Determine the machine platform first

Then, call the port occupation judgment function of each platform.

If you want to find a continuous port, as long as one of the ports is in use, it will jump out of the loop.



author = 'I316736'import osimport platformimport sysdef isInuseWindow(port):  if os.popen('netstat -an | findstr :' + str(port)).readlines():    portIsUse = True    print '%d is inuse' % port  else:    portIsUse = False    print '%d is free' % port  return portIsUsedef isInuseLinux(port):  #lsof -i:4906  #not show pid to avoid complex  if os.popen('netstat -na | grep :' + str(port)).readlines():    portIsUse = True    print '%d is inuse' % port  else:    portIsUse = False    print '%d is free' % port  return portIsUsedef isInuseAix(port):  if os.popen('netstat -Aan | grep "\.' + str(port) + ' "').readlines():    portIsUse = True    print '%d is inuse' % port  else:    portIsUse = False    print '%d is free' % port  return portIsUsedef isInuseHp(port):  if os.popen('netstat -an | grep "\.' + str(port) + ' "').readlines():    portIsUse = True    print '%d is inuse' % port  else:    portIsUse = False    print '%d is free' % port  return portIsUsedef isInuseSun(port):  if os.popen('netstat -an | grep "\.' + str(port) + ' "').readlines():    portIsUse = True    print '%d is inuse' % port  else:    portIsUse = False    print '%d is free' % port  return portIsUsedef choosePlatform():  #'Windows-7-6.1.7601-SP1'  #'AIX-1-00F739CE4C00-powerpc-32bit'  #'HP-UX-B.11.31-ia64-32bit'  #'Linux-3.0.101-0.35-default-x86_64-with-SuSE-11-x86_64'  #'SunOS-5.10-sun4u-sparc-32bit-ELF'  machine = platform.platform().lower()  if 'windows-' in machine:    return isInuseWindow  elif 'linux-' in machine:    return isInuseLinux  elif 'aix-' in machine:    return isInuseAix  elif 'hp-' in machine:    return isInuseHp  elif 'sunos-' in machine:    return isInuseSun  else:    print 'Error, sorry, platform is unknown'    exit(-1)def checkNinePort(startPort):  isInuseFun = choosePlatform()  nineIsFree = True  for i in range(1, 10):    if (isInuseFun(startPort)):      nineIsFree = False      break    else:      startPort = startPort + 1  return nineIsFree, startPortdef findPort(startPort):  while True:    flag, endPort = checkNinePort(startPort)    if (flag == True): # ninePort is ok      break    else:      startPort = endPort + 1  return startPortdef main(startPort):  firstPort=findPort(startPort)  print 'First port of nine free ports is ', firstPortif name == 'main' :  if len(sys.argv) > 1:    print len(sys.argv)    startPort = int(sys.argv[1])  else:    startPort = 500  main(startPort)


Summary of related knowledge points

OS. popen ()
You can call some shell commands of the system.

OS. popen (). readlines ()
Read the echo information after the shell command is called.


The meaning of each netstat-tnpl parameter-l or -- listening displays the Socket of the monitored server. -N or -- numeric directly uses the IP address instead of the domain name server. -P or -- programs displays the program identification code and program name using the Socket. -T or -- tcp display the connection status of TCP transmission protocol ---------- tcp 0 10.173.1.208: 4903 0.0.0.0: * LISTEN 54849/jsagent last 54849/jsagent indicates process no. 54849 process name jsagent

The above describes how to use Python to find nine consecutive idle ports. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.