So I have two machines, a laptop and a raspberry pi 4. I am trying to send UDP packets to the pi from my laptop.
C# code running on laptop:
public static void SendMessage(string msg, IPEndPoint endPoint)
{
using (UdpClient client = new())
{
var message = Encoding.ASCII.GetBytes(msg);
client.Send(message, message.Length, endPoint);
}
}
which I am calling in Main():
static void Main(string[] args)
{
new Thread(()=>
{
while (true)
{
for (int i = 0; i < 256; i++)
Networking.UDP.SendMessage("Hello World!", new IPEndPoint(IPAddress.Parse($"192.168.1.{i}"), 11000));
Console.WriteLine("Message sent");
Thread.Sleep(1000);
}
}).Start();
}
On the raspberry pi I am running this simple python script:
import socket
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
local_port = 11000
UDPsocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPsocket.bind((local_ip, local_port))
print("Now listening on port "+str(local_port))
while (True):
bytesAddressPair = UDPsocket.recvfrom(1024)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
print(str(address)+" : "+str(message))
However, the raspberry pi program does not seem to receive any messages. What am I doing wrong?
(Edit: First comment on this answer explains the reason)
Figured it out. On the pi, in order to get the local IP I was using
socket.gethostbyname(socket.gethostname())
which apparently was not the correct way to get the local IP. Someone might be able to further explain why that was not producing the correct outcome. To solve the issue I just ran hostname -I
on the pi to find the correct local IP and used that in the code, with the final receiving code being:
import socket
local_ip = "192.168.1.10" #Your local IP here obtained from terminal
local_port = 11000
UDPsocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPsocket.bind((local_ip, local_port))
print("Now listening on port "+str(local_port))
while (True):
bytesAddressPair = UDPsocket.recvfrom(1024)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
print(str(address)+" : "+str(message))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.