I am trying to send data over UDP from a Java server to a Python client on the same machine.
I can send data from a Python test server, see code below, to the Python test client just fine. However, If I try to send data from the Java test server to the Python test client, nothing seems to arrive. The Java server doesn't throw an exception.
import socket
UDP_IP = "localhost"
UDP_PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
print("listening...")
while True:
data, addr = sock.recvfrom(1024)
print("received message from: ", addr)
print("payload: ", data)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto("Hello World", ("localhost", 9999))
import java.io.*;
import java.net.*;
public class TestSender {
public static void main(String[] args) {
try {
byte[] data = "Hello world".getBytes();
int port = 9999;
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
System.out.println("Data sent");
socket.close();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
InetAddress address = InetAddress.getLocalHost();
returns the address of one of the interfaces of the machine.
As @Gomiero suggested, using either
InetAddress address = InetAddress.getByName("127.0.0.1");
// or
InetAddress address = InetAddress.getByName("localhost");
solves the problem because in this case the client bound to 127.0.0.1 and does not accept packets from any other IP address.
As @user207421 suggested in most cases the proper solution to the problem would be to bind the client to 0.0.0.0 like this:
UDP_IP = "0.0.0.0"
UDP_PORT = 9999
sock.bind((UDP_IP, UDP_PORT))
Binding the client to 0.0.0.0 resolves the issue with using InetAddress.getLocalHost() on the server-side because it makes the client accept data to any of its IP addresses.
However, I finally decided to bind the client to 127.0.0.1 now with the proper understanding of what that does, because I only want data from the local machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With