Python
/
Packages
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Packages Socket
Using Python to check if remote port is open import socket with socket.socket(...) as s: s.connect_ex((host, port))
Check port
A port is a number associated with a specific service.
"""Using Python to check if remote port is open and accessible
connect_ex() return an error indicator ...
instead of raising an exception
"""
import socket
def is_open(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
res = s.connect_ex((host, port))
if res == 0:
print("%s %s open" % (host, port))
else:
print("%s %s closed" % (host, port))
is_open('python.org', 80)
is_open('python.org', 8080)
host = input('Host: ') # localhost
port = input('Port: ') # 80
is_open(host, int(port))
Open ports
We can see which ports are open for our system.
"""Create instance of socket for every port
"""
import socket, threading
def scan_port(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
res = s.connect(("127.0.0.1", port))
print('Port %s is open' % port)
except ConnectionRefusedError:
pass
for i in range(10, 100):
thread = threading.Thread(target=scan_port, args=[i])
thread.start()
# Port 21 is open
# Port 25 is open
# Port 80 is open
➥ Questions