I am creating a socket for TCP communication and would like to know how to specify a source port.
Socket socket = new Socket();
socket.connect(dstAddress);
I am creating a socket for TCP communication and would like to know how to specify a source port.
Socket socket = new Socket();
socket.connect(dstAddress);
After creating your new socket, call bind()
with the local port number you want to use, then connect to the remote host.
@EJP is correct, though. Don't do this lightly since you can end up not being able to create the socket if something else happens to be using that port or even if your program has recently used it and closed it.
If it's not working, you may need to look at the library you're using.
You have to use InetSocketAddress, declared in the package java.net. The easiest way to use it is:
InetSocketAddress(host, port)), something like this:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("http://myserver.com", 80));
Which connect to the web server listening on the port 80 in myserver.com.