Raspberry Pi server with Scoket/Python problem - python

I'm trying to create a simple web server with Raspberry Pi 4 - Model B using sockets in Python.
The problem is that I can request from any web browser in my loclal network and the server works, but when I try to request from an external network (different IP of the Raspberry Pi server) nothing happens.
I have read a bit about it and in most of cases the problem was solved writing as IP "0.0.0.0" in the bind method of the server code, but it didn't worked for me... Is there any other error?? please help me, I'm stuck
import socket #Importa la libreria Socket
message = "Hello Internet, I'm Here!!"#Message to send to the client
IP = "0.0.0.0" #Listens to any IP client
PORT = 2020 #Server Port
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind((IP, PORT))
mySocket.listen(5)
while True:
print("\n"+"Waiting for a client...")
client1, client1_addr = mySocket.accept()
print("Got a request from client")
request = client1.recv(1024)
print("Sending Response...")
http_response = b'HTTP/1.1 200 OK\r\n\r\n'
client1.send(http_response)
byts = bytes(message, 'utf-8')
client1.send(byts) #Envia el mensaje al cliente
print("Response sent!!!")
client1.close()
mySocket.close()

Related

How do I connect to a website port using python sockets

I'm coding in Python and I'm looking for a way to connect to a website port using sockets so that I can send commands to the server. My code is:
import socket
HOST = 'www.google.com'
PORT = 80
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
This code is giving me an error "The requested address is not valid in its context". How do I do this?
You're trying to bind on Google's IP, which doesn't make sense because there isn't a network adapter connected to your computer with that IP (thus the error). You're mixing up creating a server and being a client connecting to a remote server. You want to connect to the Google server:
import socket
HOST = 'www.google.com'
PORT = 80
socket = socket.socket()
socket.connect((HOST, PORT))
# Send an HTTP GET request to request the page
socket.send(b"""
GET / HTTP/1.1
Host: www.google.com
""")
msg = socket.recv(8192)
print(msg)

PC can be UDP client but not UDP Server. Why?

I am trying to set up a Raspberry pi to transmit data to my PC via UDP. To do this, both devices are connected to my mobile hotspot.
PC IP: 192.168.78.1
RasPi IP: 192.168.78.57
There are two scripts:
UDP Server
import socket
UDP_IP = '192.168.78.1' #Used when PC is server
#UDP_IP = '192.168.78.57' #Used when RasPi is server
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((UDP_IP,UDP_PORT))
data,addr = sock.recvfrom(4096)
print(str(data))
message = "Hello, I am the UDP Server"
sock.sendto(message.encode("utf-8"), addr)
sock.close()
UDP Client
import socket
UDP_IP = '192.168.78.1' #Used when PC is server
#UDP_IP = '192.168.78.57' #Used when RasPi is server
UDP_PORT = 5005
client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
message = 'Hi, this is a client'
client_socket.sendto(message.encode("utf-8"),(UDP_IP,UDP_PORT))
data,addr = client_socket.recvfrom(4096)
print('Server Says')
print(str(data))
client_socket.close()
The client sends a message to the server and receives a message in response.
When I run the server code on the RasPi and the client code on the PC, everything works fine.
However, when I run the server code on the PC and the client code on the Raspi, it does not work.
The server gets stuck on the line data,addr = sock.recvfrom(4096) presumably waiting for a message, while the client gets stuck on the line client_socket.sendto(message.encode("utf-8"),(UDP_IP,UDP_PORT)) presumably trying to send the message.
Can anyone help me explain why the connection works with the RasPi as the server but not with the PC as the server?

Python | Connecting to a remote server using sockets

recently I've been messing around with sockets in python and i needed to connect to a remote server for a project. I know there are plenty of questions about this topic but none of the solutions worked for me and i am about to go mad if i can't get this to work.
Server code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = ''
ADDR = ('0.0.0.0', PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
conn.send("Test".encode(FORMAT))
def start():
server.listen()
print(f"[LISTENING] Server is listening on {PORT}")
while True:
connection, adress = server.accept()
thread = threading.Thread(target=handle_client, args=(connection, adress))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
Client Code:
import socket
import threading
FORMAT = "UTF-8"
PORT = 55555
SERVER = "xx.xxx.xxx.xxx" # public ip
print(f"\nconnecting... {PORT}\n")
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect(ADDR)
except:
print("Couldnt connect.")
print(client.recv(1024).decode(FORMAT))
When i change the SERVER variable in client script to my local ip (192.168.1.34), i can run these two scripts in two different pcs in the same LAN and it works well, i recieve the "Test" message in my client pc.
However, when i change the SERVER variable to my public ip and run the server in my server pc, i can't connect to the client pc. Here, my server and client pcs are NOT in the same network. Server is connected to my router whereas client is in another network. When i run the client script nothing happens and after a while i get [WINERROR 10057]
I've done port forwarding to port 55555. I tried disabling all firewalls and even creating a new rule in windows firewall to allow connections from port 55555. It still doesn't work and i can't figure out why.
If there is anyone who can see the problem here i would really appreciate it.
The only thing I can see that maybe is causing a problem is in your ADDR variable. I recently did a similar project that was successful, and in my sever code I did the equivalent of:
ADDR('',PORT)
I don't know for sure this would fix your problem, but it is my best guess from the info you provided.

SOCKET PROGRAMMING PYTHON- Putting the server code on an online server

So I have a Client - Server code in python and its running perfectly on LAN. I have this server setup on AWS and I have uploaded my server code there. In my client code, I have changed the host to the ip-address of the server online.
Unfortunately when I run the server code then the client code, there is no connection established. What could be the issue ??
Here is a part of client code:
def starting_client():
sckt = socket.socket()
host = '172.31.32.226'
port = 9090
sckt.connect((host, port))
while True:
data = sckt.recv(1024) #Data received from the server
try:
Here is part of Server code:
def SeverSocket():
try:
global host
global port
global sckt
host = ''
port = 9090
sckt = socket.socket()
except socket.error as scktCreationErrorMsg:
print(f"An error was encountered during Socket Creation: {scktErrorMsg}")
else:
print("\033[34mSocket was created as succesfull\033[0m")

Python3 server not responding to client request

I am setting up a basic python application that will listen for UDP packets at a specific port.
I am using an example code found online to begin to familiarize myself with UDP and socket connection.
When I invoke client.py and then server.py - the server does not respond and the terminal remains idle - any solutions for this problem? Below is the basic code I am working with
Client.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
Message = b"Hello, Server"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
Server.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
while True:
#data, addr = serverSock.recvfrom(1024)
data, addr = serverSock.recvfrom(1024)
print ("Message: ", data)
When I invoke client.py and then server.py
Well that's your problem--by invoking the client which sends, then later invoking the server which receives, you are preventing the two from communicating. The server needs to be running at the moment the client sends.

Categories

Resources