I have looked into many tutorials and source code for pythons socket modal to try to send a simple string between two computers.
I have made my code work independently on the PCs, but have failed to get the code to run on both. Here is the code I am currently working with:
#server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Send test","utf-8"))
clientsocket.close()
#client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1234))
while True:
full_msg = ''
while True:
msg = s.recv(8)
if len(msg) <= 0:
break
full_msg += msg.decode("utf-8")
if len(full_msg) > 0:
print(full_msg)
I am running the client script on both computers, but when I run the script on the pc not running the server, I get error the connection refused error [#10061]. I am running python 3.7, one pc is a laptop connected via internet, and one is a desktop connected to a router via Ethernet cable.
If someone knows what I need to change to get the program to run correctly, it would be much appreciated.
I am a rookie in python but I have experience in networking. Your problem sounds like a network issue to me. Before you run your program, you have to make sure there is connectivity between the two computers as you mentioned a laptop in the internet. Best way to know is pinging to each other. Your problem sounds like a typical NAT (network address translation issue).
I think you didn't open your '1234' port in your firewall.
https://www.windowscentral.com/how-open-port-windows-firewall
If you are using windows, this link can help you
Related
Honestly, I am new in python tcp sockets and I wrote a simple code for the server side.
When I run the code locally, everything is fine and I receive the message from the local server immediately, but when I put the code on a vps (linux) and run the code with python3 test.py and send a message from client to the server, server receive the message from client and waits about 1 minute to send the message back to the client and after that everything is fine and the messages transfer between server and client without any delay. I tested other platforms such as nodejs, other vps and also setting ssl for the vps and using non-blocking mode and changed the recv() buffer size too but I faced the same thing.
I used telnet and a client with python and also faced the same issue.
I will be so thankful if you help me out with this.
Best regards
client (also telnet)
import socket
c = socket.socket()
c.connect(('my_ip',56112))
c.send(bytes("1",'utf-8'))
c.recv(1024).decode()
c.close()
server
import socket
s=socket.socket()
print("socket created!")
s.bind(('0.0.0.0',56112))
s.listen(3)
print("waiting for connections!")
while True:
c, addr = s.accept()
name = c.recv(1024).decode()
print("connected with",addr,name)
c.send(bytes("hi there",'utf-8'))
c.close()
could you help me to solve this?
I am creating a software in Python3 and I need to Communicate with Whole World.
How I can create a socket over the wide area network instead of local area network!
Or Does socket programming works in such a way that client is in another network???
Plz I Need Answer as soon as possible!
Here is a example
import socket
HOSTNAME = "the host name"
PORT = xxxx
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect((HOST, PORT))
And I suggest you reed the Documentaion for waht you need.
I can successfully receive packets in Ubuntu 20.04 by calling bind() and receiving a message with recvfrom(). However, switching to Windows seems to have broken that. After clearing up a firewall issue, I can successfully receive the packet in Python 3.9, but I still cannot receive it in Python 2.7 (which is what my current program is using). When running in Python 2.7, it seems to get hung up on the recv() / recvfrom() call until I terminate it. 2.7 and 3.9 work fine in Ubuntu, so I seem to only be having this issue with Python 2.7 on Windows.
UPDATE: I did not think the IP address and port were important, as the code runs perfectly fine on Ubuntu and Windows using Python 3. I do not have access to the server-side of the code yet but will hopefully update later. What I do know is that the board is broadcasting to the particular port and IP address I have bound to below.
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_socket.bind(("192.168.11.149", 5155))
data = recv_socket.recv(1024)
print(data)
I am connecting to the particular IP intentionally, instead of accepting all IP addresses. That IP is also the correct one shown in ifconfig/ipconfig on my Ubuntu and Windows OS (on the same machine) since I am hardwired to our board through that particular port.
Is there a change in behavior between Windows and Ubuntu that I am missing? Or a change between Python 2.7 and Python 3.9 that would cause the recv() call to freeze up like this?
No change, but giving an actual example of client and server code that breaks would go a long way to getting an answer as to the behavior you see.
Here's code that works in Python 2 and Python 3. The client and server do not have to be the same version of Python.
server.py
from __future__ import print_function
import socket
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_socket.bind(('',9999))
while True:
data,addr = recv_socket.recvfrom(1024)
print(addr,'->',repr(data))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b'hello',('localhost',9999))
I'm trying to learn UDP networking so I tried the simplest code to begin with. It's a python code client-server that works perfectly when I send data to localhost or to the LAN IP from the same computer, but it doesn't work when I try to send from my computer using the public IP, and also doesn't work from another computer using private network IP or public IP.
I did the port forwarding, created the input rules for windows firewall, turned off the router internal firewall, and it still doesn't work.
When I scan my port from canyouseeme.org or using netcat it says connection refused and port closed.
Maybe somebody can guess what is happening here or what may I do to succeed?
I write the code below in case it's needed.
Server:
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = XXXX
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
message = data.decode()
print("received message:", message)
Client:
import socket
UDP_IP = "192.168.1.133"
UDP_PORT = XXXX
MESSAGE = "Hello, World!"
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
Thanks in advance.
After some investigation I have found a partial solution. I'm posting an answer because it may help some people with similar problems, but it's not the best solution yet, so the issue is still there.
I found that there's no problem in communicating within a LAN if I completely disable the firewall in both computers. I don't know why the input rules or exceptions don't work.
For networking beyond the LAN I have tried successfully to use a virtual LAN (i.e. hamachi) and there's no necessity of port forwarding nor disabling the firewall. The bad thing about hamachi is that I don't control the protocol it uses, and I don't control the way of ensuring reliability.
For the applications I'm dealing with right now I probably have enough with this solution, but it would be interesting to know more.
I have a trial version of a VPS, I want to use this as a server to send commands from a smartphone to the raspberry.
I am using http to send requests to the VPS but how can I redirect the commands received from the smartphone to the raspberry?
You can code a client-side script in Python which reads the response from the VPS each 2 seconds (or other time) and execute the command you want. E.g.
client-side script (read.py)
#client example
import socket, time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('theVPSip', 80)) # port 80 by default
TIME = 2 # amount of time to wait. Do not saturate VPS server
while 1:
time.sleep(TIME)
data = client_socket.recv(512)
print "RECIEVED:" , data
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
server-side script
Depending on what language you code, you will use a different syntax (of course). But I'll tell you what you have to do:
Register the Raspberry IP into a variable (only first time, experimenting, then let it fixed)
Register to-be-sent commands in a database
Check if the request comes from the RPi or from the phone.
RPi-> send command to execute as a return in plain text
Phone-> register data (taken from POST/GET request) into database
I suppose you could communicate with the raspberry using other model, but you would need to have a bigger control to the server and be able to run scripts of the kind of a socket connection (e.g. using Python/Java)