Basically, I want to listen to all ports using the socket module. How do I make it so that port
is = to all the open ports on the server? Any guides and or resources are highly appreciated Here is my current code.
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print('Connection from: ' + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print('from connected user: ' + str(data))
data = str(data).upper()
print('sending: ' + str(data))
c.send(data)
c.close()
if __name__ == '__main__':
Main()
Yep, create two sockets, each listening on a different port, each in a different thread. You can create one socket for each port (in fact, you must), and then use select() (look it up--it's fairly simple to use) to effectively listen to both at once, in one thread.
The ThreadPoolExecutor class in Python can be used to scan multiple ports on a server at the same time. This can dramatically speed up the process compared to attempting to connect to each port sequentially, one by one. In this tutorial, you will discover how to develop a multithreaded port scanner in Python.
Yes, a single process can listen on multiple ports, just like 80 + 443 are done. Apache has different ways to the handle the requests, the so called MPM (MultiProcessingModules). Usually you have single process and then multiple threads handling the requests as they are comming in.
A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections.
You may try all possible ports and store them in a list. Remember ports below 1024 are reserved and some of the ports may be in use. So, you will get some errors and you need to handle those if you cannot bind to that port. Also, you need a socket for each port since a socket can only listen at one port. Create a function create_socket
which returns socket, then store them is a list. If you get error while trying to connect, just pass those errors. This may not be a good approach but it will work for you.
def create_socket(port_number):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('127.0.0.1', port_number))
server_socket.listen(1)
return server_socket
socket_list = []
for port_number in range(1025,65536):
try:
socket_list.append(create_socket(port_number))
except Exception:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With