Python problem with connecting socket to server - python

I have written a simple program to connect a client to a server in python.
When I run this on my local network with my local IP address, everything works fine.
I've gotten a google cloud server and a linux VM on it. I've uploaded server.py onto the server,
but when I run it, I cannot connect from my computer with the client code.
I've tried pinging the server from my computer and that works. I also looked at which ports were being
listened to on the server side. When I left the code as below, port 5555 was not listed.
When I replaced the server in server.py by server = "", then tested for which ports were being listened to,
port 5555 was being used, but not by the public IP address, instead by the local one.
Here is the code (I've removed everything irrelevant to establishing the network connection):
server.py:
import socket
from _thread import *
import pickle
server = "34.89.182.513"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(4)
print("Waiting for a connection, Server Started")
def threaded_client(conn, player_id):
pass # I've removed this code, since it is not relevant to question
while True:
conn, addr = s.accept()
print("Connected to:", addr)
start_new_thread(threaded_client, (conn, 0))
client.py:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect("34.89.182.513", 5555)
The google cloud VM lists two different IP addresses, one private and one public. I've been using the public
one. Does that have anything to do with the problem?

Related

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 can i connect two computers with python socket?

im new here!
I have a problem with connection between two computers connected with different wi-fi's. After about 20 seconds i get information that connection can't be done.
There is my code:
SERVER:
from socket import *
lista = ['computer']
s = socket(AF_INET, SOCK_STREAM)
port = 21312
s.bind(('my ipv4', port))
s.listen(5)
while True:
for i in range (0, len(lista)):
a = str(lista[i]).encode()
c, addr = s.accept()
print("CONNECTION WITH",addr)
c.send(a)
print(a)
c.close()
CLIENT:
import socket
from socket import *
port = 21312
while True:
s = socket(AF_INET,SOCK_STREAM)
s.connect(('my ipv4', port))
odebrana = (s.recv(1024))
decoded = odebrana.decode()
print(decoded)
s.close()
Likely you are experiencing an issue because your server sits behind a Network Address Translator (NAT). This way your client cannot use the server's IP directly since it is not reachable. There are a few ways around it.
The easiest and not very practical one is: get both machines in the same network, then it should work.
Get a public IP address for the server. You can do that by hosting it on a cloud server that provides you with a public IP, e.g., aws, azure, google cloud etc.
In the old days we used hamachi to get a VPN that would connect both machines. Then they can identify each other over that VPN. Simply turn on hamachi (or any other VPN solution), run your server, then from your client (connected to the VPN), use the VPN's server IP (hamachi will provide you with one when you setup a network).
Disclaimer: I have not used hamachi in about 15 years, but just went through the process because of one of the comments below.
Seems like you can create an account, then once you turn it on you should see your v4 and v6 addresses as shown below:
Highlighted is my v4 address. I suspect you need to create a network, join both PCs in the same network and then use hamachi's IP to emulate behaviour as if they were connected via LAN.
So I faced the similar problem while sending image files between 2 computers using python sockets. I solved the issue by following this way:
First I completed writing the connection code of both server.py and client.py
Note: server.py should be in one computer and client.py should be in another computer.
server.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print(host)
server.bind((host, 12000))
server.listen()
client_socket, client_address = server.accept()
file = open('server_image.jpg','wb')
image_chunk = client_socket.recv(2048)
while image_chunk:
file.write(image_chunk)
image_chunk = client_socket.recv(2048)
file.close()
client_socket.close()
client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
server_host = 'LAPTOP-1231' # Replace this hostname with hostname printed in server.py
client.connect((server_host, 12000)) # 127.0.0.1
file = open('That_Sinking_Feeling_27.jpg', 'rb')
image_data = file.read(2048)
while image_data:
client.send(image_data)
image_data = file.read(2048)
file.close()
client.close()
Now you should add the image in the directory where client.py is located, so that you can send it to another computer (server). Rename it to img.jpg
Then, you need to run server.py in your another computer. It will print the hostname in terminal. Then copy that hostname and paste it in client.py (server_host = hostname_from_server)
Then run client.py
Finally the image will be transferred to new computer (server)

python socket does not connect to other networks

hi guys i'm studying socket in python, i'm having a hard time connecting with other machines
I have this simple code
import socket
host = ''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, 222))
print('wait...')
sock. listen(1)
conn, addr = sock.accept()
print('connected')
the code above is a server, I try to connect using this simple code
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.0.14', 222))
when I execute the client code, nothing happens, it is in an infinite wait, neither the server responds nor the client responds.
obs: this is my goal to connect to an external network on my network. The server code is running on another network, I want to connect to another network
I ran your code, and it's basically correct. But I don't think your port is perfect, it should be at least 1024.
You should make sure that the port(222) in firewall on your server computer is open.
I changed your port to 12345, it works on my computer.

How to connect my server to other machine using socket library in Python?

I am new to socket library and server side programming. I made 2 scripts which runs perfectly on my machine i.e. server.py and client.py. But when i test it on two different computers it doesn't worked.
What i want is to make my server.py file connected to client.py,
where server.py will run on my machine and it will be connected to
client.py on a separate machine at any location in the world.
I just know socket only. But if this problem can be solved by use of other library, then also it will be fine.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
s.connect((socket.gethostname(), port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
I don't know how it's possible but if it is then please answer this.
Also, i want to receive files from client.py to my machine. Is it possible in socket or i have to import any other library?
Any help will be appreciated.
The reason the client will only connect to the server running on the same computer is because you are using s.connect((socket.gethostname(), port)) instead of s.connect((host, port)). Your host IP variable is never being used. This error means that the client will be trying to connect to its own hostname, which would be itself, and so that is why it only works on one single computer.
You should modify client.py like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # Make sure this is set to the IP of the server
port = 12048
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Now you will be able to connect to a server running on a different computer.
In Client.py you're connecting the socket to socket.gethostname() instead of the ip address of your server. Now, your client is trying to a server that should be running on the same ip as the client. Logically this will work when server and client run on the same ip, but when the client resides on another machine you need to connect to the correct ip address:
s.connect((host, port))
Also, make sure that port is actually open and not blocked by another program. This website helped me open port 7777 on two different laptops and run your edited code on them. You can do the same for port 12048.
Right-click the Start button.
Click Search.
Type Windows Firewall.
Click Windows Firewall.
Click Advanced settings.
Click Inbound Rules in the left frame of the window.
Click New Ruleā€¦ in the right frame of the window.
Click Port.
Click Next.
Click either TCP or UDP.
Click Specific local ports.
Type a port number. (In this case, we will open port 12048.)
Click Next.
Click Allow the connection.
Click Next.
Click any network types you'd like to allow the connection over.
Click Next.
Type a name for the rule.
Click Finish.
I believe for a socket you have to open the TCP port but if that doesn't work you can make a new rule for the UDP port as well.

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