Pymain3664
Pymain3664

Reputation: 73

How to see the port of the router you are connected to?

I am trying to make a little/small python script that can find out the port of the router you are connected to. and if the script does not find the port it will do a print(f"port {PORT} not found") is it possible to see what the port that you are connected to or better what ports are open on your router?

Upvotes: 0

Views: 255

Answers (1)

Wasif
Wasif

Reputation: 15470

You can use socket module to try to connect the port of the router and close the socket after work is done:

import socket
from contextlib import closing

host = '192.168.0.1'
port = 25
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  if sock.connect_ex((host, port)) == 0:
    print("Port is open")
  else:
    print("Port is not open")

Here it tests with port 25 (just for example, SMTP), you can loop through range of 1 to 65536, turning to a function:

import socket
from contextlib import closing

def check_socket(host, port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
      if sock.connect_ex((host, port)) == 0:
        return True
      else:
        return False

if check_socket('192.168.0.1',25):
  print('Port open')
else:
  print('Port closed')

Upvotes: 1

Related Questions