Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting source port on a Java Socket?

Tags:

java

sockets

I'm very new to socket programming:

Is it possible to explicitly set the the source port on a Java Socket?

I am working on a client/server application in which clients could potentially be listening for replies from the server on several ports. It would be nice if I could set this reply port on the client side when initializing the Socket, so that the server would be able to determine which port to reply to on the other side.

like image 254
AndreiM Avatar asked Dec 02 '09 15:12

AndreiM


1 Answers

When using datagram sockets, the source address and port is set by the socket when the datagram is sent.

InetAddress sourceAddr = InetAddress.getLocalHost();
DatagramSocket sock = new DatagramSocket(sourcePort, sourceAddr);
DatagramPacket msg = new DatagramPacket(mbuf, mbuf.length, dstIP, dstPort);

sock.send(msg); // sent from sourcePort to dstPort

sourceAddr is a little redundant in this example, new DatagramSocket(sourcePort) would bind to the preferred best-choice address, but if you need to specify the source IP in addition to port, that's how.

For both types of socket, using bind(new InetSocketAddress(port)) will choose an appropriate local source address and the specified port, and port 0 will choose an appropriate local port as well.

All retrievable with getLocalAddress() and getLocalPort().

like image 144
davenpcj Avatar answered Sep 24 '22 14:09

davenpcj