- Python program to check if a network port is open
- What is Socket Programming
- Checking if the network port is open using Python programming
- betrcode / README.md
- Footer
- How to check if a network port is open in Python?
- Method 1: Using socket library
- Method 2: Using a library like telnetlib
- Method 3: Using a library like nmap
Python program to check if a network port is open
In this Python programming article, you are going to learn how to check if a particular port is open. We are using socket.socket() and socket.connect_ex() to check if a network port is open. Before going into programming first let’s understand what is Socket Programming and some basic terminology of socket programming.
Before we go forward, we first need to know about socket programming.
What is Socket Programming
Socket Programming is a way of connecting two nodes on a network in order to communicate with each other. One socket or node listens to a particular port at an IP address and the other socket reaches out to the other port for creating a connection. In simple terms, they are called client-server programming. They are the backbones behind web browsing.
Python has a socket library for implementing socket programming. Let’s make a simple socket
import socket as sock s = sock.socket(sock.AF_INET, sock.SOCK_STREAM)
Here we made a socket and passed two parameters. The first parameter is AF_INET refers to address-family ipv4 and the second parameter SOCK_STREAM refers to the connection-oriented TCP protocol.
Checking if the network port is open using Python programming
Below are given steps to perform our task in Python:
1) First import the socket library as sock.
2) Create a socket object by calling sock.socket(family, type) with the family set to sock.AF_INET and the type set to SOCK_STREAM.
3) Create a destination as a tuple containing the IP address and the desired port number.
4) To check port is open call sock.connect_ex(destination) which returns 0 if the port is open, 1 if the port is close.
5) After checking the port is open, then socket by using socket.close().
import socket as sock create_socket = sock.socket(sock.AF_INET, sock.SOCK_STREAM) destination = ("127.0.0.1", 80) result = create_socket.connect_ex(destination) if result == 0: print("Port is open") else: print("Port is not open") create_socket.close()
betrcode / README.md
Using Python to check if remote port is open and accessible.
- Open a Python prompt
- Run the script in is_port_open.py
- Call isOpen with a host and a port parameter. Example: isOpen(«www.google.com», 80)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import socket |
def isOpen ( ip , port ): |
s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) |
try : |
s . connect (( ip , int ( port ))) |
s . shutdown ( 2 ) |
return True |
except : |
return False |
Maybe improve script to take command line arguments.
Simple and precise! From what I can tell, however, this does not seem to be working. Take for example the following:
This will never finish. Should I be doing something different?
Could it because of the timeout?
If that’s the case then maybe could add socket.settimeout()?
for i in range(10): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) s.connect((ip, port)) print ip + " is UP" except: time.sleep(1) finally: s.shutdown(socket.SHUT_RDWR) s.close()
for i in range(10): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) s.connect((ip, port)) print ip + " is UP" except: time.sleep(1) finally: s.shutdown(socket.SHUT_RDWR) s.close()
This doesn’t work, please check code before replying. If the connection fails, the finally block runs, but s is not connected, therefore shutdown fails.
Full example, tested with a retry and delay between retries:
#!/usr/bin/python import socket import time ip = "google.com" port = 443 retry = 5 delay = 10 timeout = 3 def isOpen(ip, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) try: s.connect((ip, int(port))) s.shutdown(socket.SHUT_RDWR) return True except: return False finally: s.close() def checkHost(ip, port): ipup = False for i in range(retry): if isOpen(ip, port): ipup = True break else: time.sleep(delay) return ipup if checkHost(ip, port): print ip + " is UP"
Another option for anyone interested is I’ve incorporated the above into a Python app with argument parsing that uses SMTP to send alerts. It also runs in docker: https://github.com/Fmstrat/server-monitor
This also now support UDP.
Cheers for sharing this code. It worked really well for me.
Yes an old thread but still usefull. Can anyone shed some light as to how you can have multiple hosts that it polls until the app is exited?
as in..
domain1.com host id UP
domain2.com host id UP
domain3.com host id DOWN
domain4.com host id UP
#!/usr/bin/python3
import sys
import socket
import time
ip = «domain.com»
port = 443
retry = 1
delay = 1
timeout = 2
def isOpen(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
def checkHost(ip, port):
ipup = False
for i in range(retry):
if isOpen(ip, port):
ipup = True
break
else:
time.sleep(delay)
return ipup
if checkHost(ip, port):
print ip + » port » + str(port) + u» is \u001b[32;1mUP!\u001b[0m»
else:
print ip + » port » + str(port) + u» is \u001b[31;1mDOWN!\u001b[0m»
async def wait_host_port(host, port, duration=10, delay=2): """Repeatedly try if a port on a host is open until duration seconds passed Parameters ---------- host : str host ip address or hostname port : int port number duration : int, optional Total duration in seconds to wait, by default 10 delay : int, optional delay in seconds between each try, by default 2 Returns ------- awaitable bool """ tmax = time.time() + duration while time.time() tmax: try: _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5) writer.close() await writer.wait_closed() return True except: if delay: await asyncio.sleep(delay) return False
async def wait_host_port(host, port, duration=10, delay=2): """Repeatedly try if a port on a host is open until duration seconds passed Parameters ---------- host : str host ip address or hostname port : int port number duration : int, optional Total duration in seconds to wait, by default 10 delay : int, optional delay in seconds between each try, by default 2 Returns ------- awaitable bool """ tmax = time.time() + duration while time.time() tmax: try: _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5) writer.close() await writer.wait_closed() return True except: if delay: await asyncio.sleep(delay) return False
Thanks this is EXACTLY what I was looking for.
async def wait_host_port(host, port, duration=10, delay=2): """Repeatedly try if a port on a host is open until duration seconds passed Parameters ---------- host : str host ip address or hostname port : int port number duration : int, optional Total duration in seconds to wait, by default 10 delay : int, optional delay in seconds between each try, by default 2 Returns ------- awaitable bool """ tmax = time.time() + duration while time.time() tmax: try: _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5) writer.close() await writer.wait_closed() return True except: if delay: await asyncio.sleep(delay) return False
While reading this, I had tears of joy. Many thanks!
Very good, replace ping command,haha!
Thank you very much. Works out of the box 🙂
Small note, this can be sped up by using connect_ex instead of connect . The first call will not raise any exceptions (except for No host found , but that’s standard) and is faster than the second one. Example:
def isOpen(ip, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) try: is_open = s.connect_ex((ip, int(port))) == 0 # True if open, False if not if is_open: s.shutdown(socket.SHUT_RDWR) except Exception: is_open = False s.close() return is_open
async def wait_host_port(host, port, duration=10, delay=2): """Repeatedly try if a port on a host is open until duration seconds passed Parameters ---------- host : str host ip address or hostname port : int port number duration : int, optional Total duration in seconds to wait, by default 10 delay : int, optional delay in seconds between each try, by default 2 Returns ------- awaitable bool """ tmax = time.time() + duration while time.time() tmax: try: _reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=5) writer.close() await writer.wait_closed() return True except: if delay: await asyncio.sleep(delay) return False
Thank you for the code. It works, but in python3.6, I get an exception like this ‘StreamWriter’ object has no attribute ‘wait_closed’ . Could you tell me how to fix it. Please
Footer
You can’t perform that action at this time.
How to check if a network port is open in Python?
In computer networking, a port is a communication endpoint. It is a logical construct that identifies a specific process or a type of network service. When a client wants to communicate with a server, it connects to a specific port on the server. In order to determine if a network port is open or not, one can try to establish a connection to it and check if the connection is successful or not. In Python, there are several ways to check if a network port is open, and in this article, we will discuss some of the most popular methods.
Method 1: Using socket library
To check if a network port is open in Python, you can use the socket library. Here are the steps to do it:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('localhost', 8080))
if result == 0: print("Port is open") else: print("Port is not open")
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) result = s.connect_ex(('localhost', 8080)) if result == 0: print("Port is open") else: print("Port is not open")
This code creates a TCP socket ( SOCK_STREAM ) and tries to connect to the specified port ( 8080 in this example) on the localhost ( ‘localhost’ ).
The connect_ex() method returns 0 if the connection was successful, or an error code if the connection failed. If the result is 0 , then the port is open. Otherwise, it is not open.
Method 2: Using a library like telnetlib
To check if a network port is open in Python using the telnetlib library, follow these steps:
tn = telnetlib.Telnet(host, port)
Replace host with the hostname or IP address of the server you want to check and port with the port number you want to check.
The read_until method reads the response until it finds the specified string. In this case, we’re looking for a newline character ( \n ).
if "Connected" in response.decode('utf-8'): print("Port is open") else: print("Port is closed")
The decode method is used to convert the response from bytes to a string so we can check if it contains the word «Connected».
import telnetlib host = "example.com" port = 80 tn = telnetlib.Telnet(host, port) response = tn.read_until(b"\n") if "Connected" in response.decode('utf-8'): print("Port is open") else: print("Port is closed")
This code will check if port 80 is open on the server example.com . If the port is open, it will print «Port is open». Otherwise, it will print «Port is closed».
Method 3: Using a library like nmap
Here are the steps to check if a network port is open using nmap library in Python:
Here, we are scanning the host ‘127.0.0.1’ for open ports between 22 and 443.
protocols_list = nm[hosts_list[0]].all_protocols()
Here, we are getting the protocols for the first host in the hosts_list.
tcp_scan = nm[hosts_list[0]]['tcp']
Here, we are getting the TCP scan results for the first host in the hosts_list.
port_state = tcp_scan[80]['state']
Here, we are getting the state of port 80.
has_tcp = nm[hosts_list[0]].has_tcp(80)
Here, we are checking if the first host in the hosts_list has port 80 open.
That’s it! You can use these steps to check if a network port is open using nmap library in Python.