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
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()
.