Reputation: 893
I've been struggling with this for a few hours now and really just don't know where to go from here. I've got an arduino uno with a wifi shield connected to a network, and a laptop with Ubuntu connected to the same network. I'm using the arduino Wifi Library to connect to the network.
I can send data to my laptop from the arduino and print it successfully using: sudo nc -l 25565
I am also trying to use the following python code to do the same thing I did with nc
which is also being run as sudo
just in case:
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 25565
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
(conn,addr) = s.accept()
print 'Connection address: ',addr
while True:
data = conn.recv(BUFFER_SIZE)
if not data: break
print 'received data: ',data
conn.send('ECHO')
conn.close()
s.close()
But it just hangs at (conn,addr) = s.accept()
. Using a client python script on the same laptop I can connect to the above server and I can send data to it which the server then prints.
I just have no idea why nc
will print from the arduino but the python server script won't, even though it will print from a python client. Could the arduino libraries be failing to follow some standard that python expects? Thanks in advance.
Upvotes: 0
Views: 4205
Reputation: 168886
No, the arduino libraries are not "failing to follow some standard".
Your program is binding to the localhost
interface, IP address 127.0.0.1
. This means that only programs running on the same PC will be able to connect to your Python server.
Try this:
s.bind(('',TCP_PORT))
Reference:
https://docs.python.org/2/library/socket.html :
For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents
INADDR_ANY
, and the string'<broadcast>'
representsINADDR_BROADCAST
. The behavior is not available for IPv6 for backward compatibility, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.
https://docs.python.org/2/howto/sockets.html#creating-a-socket :
A couple things to notice: we used socket.gethostname() so that the socket would be visible to the outside world. If we had used s.bind(('localhost', 80)) or s.bind(('127.0.0.1', 80)) we would still have a “server” socket, but one that was only visible within the same machine. s.bind(('', 80)) specifies that the socket is reachable by any address the machine happens to have.
Upvotes: 4