java DatagramSocket gets same port on linux

N

neutrondba

Hello,

I am running into a problem where if I instantiate a
DatagramSocket
on Red Hat Linux , the JAVA VM returns back the same port on
subsequent calls
of instantiating a DatagramSocket. I need to instantiate multiple
Datagram Sockets from the same Java VM because I have a multithreaded
client. Because it returns the same port for multiple clients the
responses that come back from a DNS server returns results to the
incorrect client. This problem does not occur on Winows machines

I made a simple test of instantiating multiple times and found this to
be the case

while (true){
try {
clientSocket = new DatagramSocket();

System.out.println(" local " + clientSocket.getLocalPort());
timeSocket.close();
}
catch (SocketException excpt) {
System.err.println("Unable to bind UDP socket: " +
excpt);
System.exit(1);
}
try{
Thread.sleep(100);
}catch(Exception e){

}
}

[ classes]# java -classpath . tutorial.ClientSocket

local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903
local 32903

Anyone have any ideas why it is returning the same port for each
instantiaton?
 
P

pfalstad

Why are you closing the socket each time? It's returning the same port
because each time you close the socket, the port is freed up to be
reused. Am I missing something? If you want n different ports, open n
different sockets.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top