Windows not accepting Socket Connections when running as service - python

I´m writing a small application on Windows 10 in Python.
It should listen on TCP socket connections and receive some data. No Responses are required from the application. Application must be runned as a windows service.
When running in Debug Mode it works perfectly. It receives the data, and processes it.
When running as a Service (with pyinstaller and pywin32 packages) no data is received and nothing happens.
def sockThread(port: int, interface: str):
global sock
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((interface, port))
except socket.error as e:
logging.error('could not open socket connection with' + interface + ":" + str(port))
logging.error('error: ' + str(e))
return
logging.info("socket timeout: " + str(sock.gettimeout()))
#run:
while stop==False:
logging.info("socketthread starting, listening on:" + interface + ":" + str(port))
try:
sock.listen(1)
c, addr = sock.accept()
#logging.info("socketthread connection accepted")
except socket.error as e:
logging.error('error while listening to socket:' + str(e))
else:
data = c.recv(2048)
#logging.info("data received: " + str(data))
processStarter.startSubProcess(data)
logging.error("socket thread leaving")
Code is tested with a Raspberry Pi command line:
netcat -w1 192.168.178.27 60000 <testfile.txt
Is there any difference in the configuration of a Windows Service and Application?

Found the solution to "Windows not accepting connections": Windows Firewall Rules are different for a Service and an Application inside Debugger.
So there are still some bugs in my Code, but the connections are now accepted now, when running as a Service.

A Windows Service has to have specifically registered port to listen on.
The command is:
netsh http add urlacl url=http://+:PORT/
More on add urlacl is here: https://learn.microsoft.com/pl-pl/windows/win32/http/add-urlacl

Related

How to check if UDP port is open? (python)

I am trying to write a port scanner with python and there is an issue with UDP ports. Google says that I have to send some request and either recieve TimeoutError, meaning server got the message via the port and the port is opened, or recieve ICMP message "Destination unreacheable(Port unreachable)", meaning port is closed. I am able to see ICMP message in Wireshark but have no idea how to make python see it as well.
Now my code for UDP looks like this:
def udp_connection(ip, port, timeout):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(timeout)
try:
s.sendto(b'test', (ip, port))
data, addr = s.recvfrom(1024)
return "[+] UDP Port Open: " + str(port) + str(data) + '\n'
except TimeoutError:
return "[+] UDP Port Open: " + str(port) + 'kinda no response or something' + '\n'
except:
return "[+] UDP Port Closed: " + str(port) + '\n'
and this always returns TimeoutError.
Also tried a solution found on stackoverflow to add a raw socket with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as s1: and recieve data with data, addr = s1.recvfrom(1024) instead of data, addr = s.recvfrom(1024) but haven't succeeded
Python throws ConnectionResetError exception when trying to receive response from (ip,closedPort) because receiving the ICMP "Destination unreacheable(Port unreachable)" message but the ICMP packet may be blocked by windows firewall, python will not receive it and... that's it. I literally just had to turn it off to make my code work

Python Socket connection over 2 different networks

I know there are tons of questions like this but none of them helped me. I am trying to connect computer and vm that are on 2 different networks.
Server:
import socket
HOST = '0.0.0.0'
PORT = 1080
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print("\n Listening on port " +str(PORT)+ ", waiting for client to connect...")
client_socket, (client_ip, client_port) = server_socket.accept()
print("[+] Client " +client_ip+ " connected!\n")
while True:
try:
command = raw_input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(command)
else:
continue
except Exception,e:
print("[-]Something went wrong")
continue
if(command == "stop"):
break
data = client_socket.recv(1024)
print(data + "\n")
client_socket.close()
As you see,i opened a server that listens on port 1080 and accepts all connections.I turned off the windows firewall and the SPI Firewall. I also forwarded the port 1080( nmap scan finds it and says its open).
Client:
import socket
import platform
HOST = "output of whatismyipaddress.com when run on server computer"
PORT = 1080 # port(same as on server.py)
connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connection_socket.connect((HOST, PORT))
print("\n[*] Connected to " +HOST+ " on port " +str(PORT)+ ".\n")
while True:
command = connection_socket.recv(1024)
split_command = command.split()
print("Received command : " +command)
if (command == "stop"):
break
elif (command == "info"):
connection_socket.send(("Info: " + str(tuple(platform.uname()))))
connection_socket.close()
So client is sending data to server and server is sending commands to client.
I assume client doesn't need to have any port forwarded.
The client(vm) was connected to Android HotSpot. The server was connected to router that had port forwarded. I've choose bridged connection for vm and connected my external wifi card for it.
Server started listening and client started. I get error that the server did not properly respond after period of time when trying to connect. I also tried connecting using default gateway but no success.
I am a little confused about it since Wikipedia says:
A default gateway in computer networking is the node that is assumed to know how to forward packets on to other networks. Typically, in a TCP/IP network, nodes such as servers, workstations and network devices each have a defined default route setting, (pointing to the default gateway), defining where to send packets for IP addresses for which they can determine no specific route.
Which I understand as it is used to communicate over 2 different networks?
Anyways, does anyone know how can I fix this issue and what am I doing wrong?

Python ConnectionRefusedError: [Errno 61] Connection refused

Ive seen similar questions but they I couldn't fix this error. Me and my friend are making a chat program but we keep getting the error
ConnectionRefusedError: [Errno 61] Connection refused
We are on different networks by the way.
Here is my code for the server
import socket
def socket_create():
try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error" + str(msg))
#Wait for client, Connect socket and port
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error" + str(msg) + "\n" + "Retrying...")
socket_bind
#Accept connections (Establishes connection with client) socket has to be listining
def socket_accept():
conn, address = s.accept()
print("Connection is established |" + " IP:" + str(address[0]) + "| port:" + str(address[1]))
chat_send(conn)
def chat_send(conn):
while True:
chat =input()
if len(str.encode(chat)) > 0:
conn.send(str.encode(chat))
client_response = str(conn.recv(1024), "utf-8")
print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()
main()
And my client code
import socket
#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))
#gets chat
while True:
data = s.recv(1024)
print (data[:].decode("utf-8"))
chat = input()
s.send(str.encode(chat))
This may not answer your original question, but I encountered this error and it was simply that I had not starting the server process first to listen to localhost (127.0.0.1) on the port I chose to test on. In order for the client to connect to localhost, a server must be listening on localhost.
'127.0.0.1' means local computer - so client connents with server on the same computer. Client have to use IP from server - like 192.168.0.1.
Check on server:
on Windows (in cmd.exe)
ipconfig
on Linux (in console)
ifconfig
But if you are in different networks then it may not work. ipconfig/ifconfig returns local IP (like 192.168.0.1) which is visible only in local network. Then you may need external IP and setting (redirections) on your and provider routers. External IP can be IP of your router or provider router. You can see your external IP when you visit pages like this http://httpbin.org/ip . But it can still need some work nad it be bigger problem.
You need simply to start server at first, and then run the client_code.
In VS Code i've opened 2 terminals. One for the server_code to be running While True, and the other one for the client_code
So this may not fix your question specifically but it fixed mine and it can help someone else I work with vscode and I use some extension that runs my code so when you want to run your server run it on your CMD or Terminal and run your client in vscode it helped me (maybe importat I work on mac so maybe spesific OS problem)
If you are connecting to a host:port that is open but there is no service bound to it you may see this IIRC. Eg with ssh you sometimes see this while attempting to connect to a server that is booting but sshd is not running.
This Code Not Valid For Chatting, you have to use unblocking sockets and select module or other async modules

Python : How to connect socket on different network

I have begun learning Socket Programming and Issue I faced is. I am unable to connect Sockets when On two different network ( To be specific : I am using Web-host and Cgi programming to create python socket Server and my goal is to connect to that socket using desktop client python application )
My Server Coad : Location Public_html/cgi-bin/serverSocket.py
#!/usr/bin/python
print "Content-type: text/html\n\n";
import cgitb
import socket
cgitb.enable()
def main():
host = 'localhost'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(10)
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.decode()))
data =str(data.decode()).upper()
print ("sending :" + str(data))
c.send(data.encode())
if __name__ == '__main__':
main()
And Client Program : Location On My Local Computer C:/Desktop
#!/usr/bin/python
print "Content-type: text/html\n\n";
#Client Socket Program
import socket
def main():
host = 'www.mywebsite.com'
port = 8111
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,port))
except socket.error as e:
print(str(e))
message=input("-> ")
while message != 'q':
s.send(message.encode())
print("Sent Message")
data=s.recv(1024)
print('Recieved from server :', str (data.decode()))
message=input("->")
s.close()
if __name__ == '__main__':
main()
| Error Encountered is : [WinError 10060] |
| Python Server uses : Python 2.6.6 |
| Python Client :python 3.4 |
While using This On same system (ie: Local host as Server and client works Fine)
PS: Also link if there is any tutorial on this,Also advice some configuration if must be made.
If you want them to access each other, use public IPs. (Public IP Address) You would also need to port-forward (this is different for every router so I can't explain, look it up). Otherwise, the port you want to access will not be accessible from other networks. When you port-forward, that port on your Public IP Address can then be accessed.
Python 2 and 3 handle sockets differently! See here this question for example. What you could do as a quick workaround is to change your client start line to "#!/usr/bin/env python2.7" to force the client to use python 2 as well, that should fix your problem.

Unable To Connect Python Sockets On Different Computers

I recently wrote a code for a small chat program in Python. Sockets connect fine when I connect them from different terminals on the same system. But the same doesn't seem to happen when I connect them from different computers which are connected over the same Wifi network.
Here's the server code:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys, select
host = "192.168.1.101"
port = 8888
connlist = []
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
connlist.append(s)
s.bind((host,port))
print "Socket Successfully Binded."
s.listen(10)
print "Socket is Now Listening."
except Exception, e:
print "Error : " + str(e)
sys.exit()
def air(sock,message):
for socket in connlist:
if socket != sock and socket != s:
try:
socket.sendall(message)
except:
connlist.remove(socket)
while 1:
read_sockets,write_sockets,error_sockets = select.select(connlist,[],[])
for sock in read_sockets:
if sock == s:
conn, addr = s.accept()
connlist.append(conn)
print "Connected With " + addr[0] + " : " + str(addr[1])
else:
try:
key = conn.recv(1024)
print "<" + str(addr[1]) + ">" + key
data = raw_input("Server : ")
conn.sendall(data + "\n")
air(sock, "<" + str(sock.getpeername()) + ">" + key)
except:
connlist.remove(sock)
print "Connection Lost With : " + str(addr[1])
conn.close()
s.close()
Here's the client script:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys
host = "192.168.1.101"
port = 8888
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
s.connect((host,port))
print "Connected With " + host + " : " + str(port)
except socket.error, e:
print "Error : " + str(e)
while 1:
reply = raw_input("Client : ")
s.send(reply)
message = s.recv(1024)
print "Server : " + message
s.close()
When I try to connect The client From a different computer I get this error :
Error : [Errno 10060] A Connection attempt failed because the connected party
did not respond after a period of time, or established connection failed
because connected host has failed to respnd.
Your are binding your server only to the local host, so that connections from other hosts are blocked.
Try:
s.bind(("0.0.0.0",port))
I experienced this problem and it took me a many hours to figure this out and I found that (like many others said #Cld) it is your firewall blocking the connection. How I fixed this:
Try to run the server onto the machine that you trying to connect from.
(For example, if you want to run the server on machine A and connect from machine B, run the server on machine B).
If you are on windows (I am not sure about Mac or Linux) it will popup with with the firewall pop-up, which will allow you to give permission to your program to access your private network.
Simply tick the box that says:
"Private networks, such as my home or work network"
and Press allow access
That's it! You've fixed that particular issue. Now feel free to test the server on that machine or close the server and go back to your main machine, which will host that server and run it. You should see that it is now working.
I hope this has helped you, as it is my first post!
EDIT: I also did what #Daniel did in his post with changing the s.bind to include '0.0.0.0'.
I had this same problem for quite sometime, and creating tcp tunnels with ngrok worked for me. You can check it out here
For simple sockets application on your pc, just expose the port you're using by ngrok tcp <port_number>, bind the server socket to localhost and port exposed, and use the url of the tunnel with the port number at client side (typically looks like 0.tcp.us.ngrok.io and a port number).
You can even make multiple tunnels on the free account (needed in my case) by specifying the --region flag: https://ngrok.com/docs#global-locations

Categories

Resources