Carlos Albaladejo Carlos Albaladejo - 8 days ago 5
Java Question

Setting source port on udp socket

We've developed a Java application that sends several UDP datagrams to the very same destination IP address. Obviously the destination port is always the same one, but we can't seem to be able to set the source port to remain the same on each datagram.

If the data package we send is bigger than MTU the package is properly splitted over the same source port, but once we send a new data package the source port changes, generating a new firewall session (which network admin has warned us to be very bad due to the amount of sessions the application is generating).

Right now we're sending the packages with the following statement:

We've tried several approaches and the result is always the same, we can't seem to be able to set the source port to a fixed value.

Edit- pasting actual code:

private boolean sendImage(byte[] imageData, InetAddress address,
int port) throws UnknownHostException, SocketException {

boolean ret = false;


DatagramSocket socket = null;

try {
socket = new DatagramSocket();
DatagramPacket dp = new DatagramPacket(imageData, imageData.length, address, PUERTO_UDP);
socket.send(dp);
ret = true;
} catch (IOException e) {
Main.lanzarExcepcion(e);
ret = false;
} finally {
if (socket != null) {
socket.close();
}
}

return ret;
}


Thanks for your time!

Answer

I think your issue is that you are closing the actual DatagramSocket instead of reusing the same , and simply call socket.send(DatagramPacket). If you cant keep the client socket open , then you could even define the clients port like : DatagramSocket clientSocket = new DatagramSocket(9743); so each time you are calling a new clientSocket , it will get the same port or it will throw a java.net.BindException: Address already in use: Cannot bind

This will not solve the network sessions issue, because you are opening a new UDP Socket. Also i suspect that your network admin , sees the previous sessions , because you are not closing the UDP Sockets at all , but simply spawning them