My application uses Python socket
so I had to to add a firewall exception to be able to receive data through sockets. I've frozen the app using PyInstaller to be able to distribute it for Windows computers. To add the firewall exception, I use below code:
command1 = f'netsh advfirewall firewall add rule name="{rule_name}" profile=any protocol=any enable=yes DIR=In program="{app_path}" Action=Allow'
command2 = f'netsh advfirewall firewall add rule name="{rule_name}" profile=any protocol=any enable=yes DIR=Out program="{app_path}" Action=Allow'
subprocess.run(command1, shell=False, stdout=DEVNULL, stderr=DEVNULL)
subprocess.run(command2, shell=False, stdout=DEVNULL, stderr=DEVNULL)
In order to add this exception, I use this code to get elevated permissions:
try:
isAdmin = ctypes.windll.shell32.IsUserAnAdmin()
except AttributeError:
isAdmin = False
if not isAdmin:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
The user is prompted an elevation confirmation Window and if he accepts it, the firewall exception is created correctly and the application is working fine. However, if the application is closed and runned again, I check if the firewall rules exists and if so I don't ask for elevated permissions again.
My problem is that without elevated rights, the application is not able to open a socket to a remote host and on the opposite, if the user runs the application with elevated rights or if the application asks for it, it will work.
What should I do to get the app working without elevated rights (except for the first time when the firewall exception is created) ?
EDIT
I use these parameters to create and connect the socket:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((192.168.x.x, 80xx))
EDIT 2
I just noticed that I'm able to accept incoming connections and send data (server mode) but I can't establish external connection and receive data (client mode).