Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error connecting to raspberrypi using python socket

I am trying to connect to my raspberry pi over the network. I'm running python as the server on the raspi. Here is the simple server code I got off the web:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 80
print (host)
print (port)
serversocket.bind((host, port))

serversocket.listen(5)
print ('server started and listening')
while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    clientsocket.send("data is sent".encode())

Test client code:

import socket

s = socket.socket()
host = "192.168.1.247"
port = 80
s.connect((host,port))
s.send('randomData'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
s.close

I have tested it on other computers and these work fine. When raspi is the CLIENT and the other computer is the server it works fine. But, when raspi is SERVER and the other computer is the client, I always get the same error: "No connection could be made because the target machine actively refused it"

Trying to connect using c#:

TcpClient client = new TcpClient("192.168.1.247", 80)

throws error: "No connection could be made because the target machine actively refused it"

Note: -raspi as client to raspi as server works fine. -I have done some research and it seems that the most common causes of this is a firewall or bad router. --I don't think its the router cause I can do a raspy to other computer just fine. --I'm using the Raspbian “wheezy” Debian distro and I don't think that comes with a firewall.

Any help would be appreciated. Thanks!

like image 978
Ryan Lee Avatar asked Oct 06 '22 10:10

Ryan Lee


1 Answers

I think the problem is that you're using socket.gethostname() which will return the hostname and not the ip. Most probably this means that your socket will bind to that hostname but not the IP, this means that python will only listen to connections to the hostname which probably is: raspberrypi

Most probably your machines does not know about that hostname, so you want to use this instead:

socket.gethostbyname(socket.gethostname())

Which it also says in the documentation

The thing to remember is that hostname and IP is not the same thing. However you could bind your hostname to the IP that you have in the /etc/hosts file like this:

192.168.1.247 raspberrypi

like image 136
Daniel Figueroa Avatar answered Oct 10 '22 03:10

Daniel Figueroa