Establishing a socket connection between computers? - python

I was learning about networking and I have some trouble understanding what went wrong.
I created a Client and a Server script:
Server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print ("Got connection from: " ,addr)
c.send("Thanks".encode('utf-8'))
# c.sendto(("Thank you for connection").encode('utf-8'), addr)
c.close()
and Client:
import socket
s=socket.socket()
host=socket.gethostname()
port = 12345
s.connect((host,port))
c=s.recv(1024)
print (c)
s.close
When I am trying to run from my computer I have no problem (both scripts)
But when I am running the Client from another Computer, the following error pops up for the Client: ConnectionRefuseError: WinError10061 No connection could be made because the target machine actively refused it.
Got any idea what could fix this?

The problem was that I wasn't referring to the server IP when running from another computer, I fixed it by passing the server IP, in the client script, like this host = "10.x.x.x"
Sorry for creating a useless question!

Related

Cannot connect two devices with socket (python)

I have an Ipad and a raspberry pi. I want to broadcast a simple message from my ipad to my raspberry pi using python's library: "socket". I have a file called server.py in my raspberry pi. I have another file called client.py in my Ipad. server.py should await a connection from the Ipad, and accept it. client.py should send the broadcast message.
server.py
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
client.py
import socket
HOST = "0.0.0.0"
PORT = 9999
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
I first ran server.py on my raspberry pi, then ran client.py on my Ipad. However, the following error message greeted me when I ran client.py:
[Errno 61] Connection refused
I made sure the server was running properly, and I checked where the client was connecting to. It should have worked.
Please help me.
I would like to point out that there are so many mistakes in that code. I presume that you are totally new with sockets.
(Also try putting 'your-server's-local-ip' in the bind_ip and HOST in server.py and client.py respectively if both of your server and client are connected to the same network)
Even though you connect with the server you'd still get greeted with another errors.
Let me start with server.py:
In server.py you are using handle_client function to recieving a message from the client while at the client end you are not sending anything.
After that you're recieving the message from the client while the client is not sending anything.
There is no broadcast function for sending the message to every connected client
The main issue is that you've not learned the basics of the sockets, my only suggestion to you would be to, start things small and then increase the complexity but here, that case is totally opposite.
You can also refer to this video to learn the basics : https://youtu.be/u4kr7EFxAKk

Socket with Python

I read some of the Sockets documentation and watched some videos on the subject, I tried to make the sockets connection. First, I tried it with my internal IP, ran it on different endpoints and everything worked. I tried it with my external IP and it failed, I tried to run the same application on different devices, I ran server.py on my PC, and I ran client.py on my cell phone. No error message appeared, but the connection did not start.
Server code:
import socket
s = socket.socket()
print("Socket successfully created")
port = 12345
s.bind(('Meu IP', port))
print("socket binded to %s" %(port))
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print('Got connection from', addr )
c.send('Thank you for connecting'.encode())
c.close()
Client code:
# Import socket module
import socket
s = socket.socket()
port = 12345
s.connect(('IP', port))
print (s.recv(1024).decode())
s.close()
I think the problem is the IP, I think I should put the valid external IP instead of the internal IP, but I don't know how to do that, because when I try this, an error appears. I just need to know how to create a socket between two machines on different networks. I have been looking for a solution to this problem for a long time. If any of you can help me, I appreciate it.

How to exchange data on different networks using sockets?

I know this was already asked but the previous questions didn't help. I'm trying to send some data using sockets. Specifically I'm using my laptop as server and a Linux emulator (Termux) on my smartphone as a client. Here below you can see the two Python codes. For the server:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
s.close()
And for the client:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
s.close()
When I'm connected to the same WiFi and in HOST (in both codes) I put the IP I see from ipconfig (192.168.---.---) everything works. It also works if in the HOST of the server I put 0.0.0.0.
However, when I put the IP of the machine (that I can see on https://whatismyipaddress.com/) and instead of using the WiFi I use the phone connection I get: ConnectionRefusedError: [Errno 111] Connection Refused.
Can someone explain me how can I connect client and server when the networks are different? I have been stuck with this for a while.
I also tried to open a port on the Firewall following this procedure and put it in the code instead of 5555 but still it didn't work.
Thank you in advance for the help.

Python Socket Programming - Server Client basic

I recently started learning socket programming with python. Starting with the most basic scripts of server and client on the same computer, I wrote the following code.
Server.py
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)
while True:
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" %str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))
I'm using spyder IDE. Whenever I run the client in the IPython Console, this is what I get:
"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it."
and whenever I run the Server I get an unending process.
So, what should I do to make this work?
Thank you for any help!
Credits :- http://www.bogotobogo.com/python/python_network_programming_server_client.php
Try changing socket.gethostname() to socket.gethostbyname(socket.gethostname()). gethostbyname returns the ip for the hostname. You want to setup a socket to connect to an ip, port. Alternatively, since you are running everything locally, just set your host to "127.0.0.1" directly for both the client/server.

Python server client socket

I've tried to connect two computers with a socket in Python and I don't know why it doesn't work. The files are from internet and it compiles for me but without any results.
The server.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = ''
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
and the client.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = # here I put the ip of the server's laptop
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
What's wrong?
You have to run the server first. Then run the client at the same time with the IP of the server (I used localhost because it was running on one computer, maybe you should try if that works). The code worked fine for me, every time I ran the client, the server printed a message. If it doesn't work for you, maybe your firewall is not letting you open ports.
Just for the future, please always post any error messages you see.
BTW, isn't this the Python Documentation example for sockets?

Categories