1

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);
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
wotan2009
  • 193
  • 3
  • 14
  • 3
    This is generally a very bad idea. It limits you to one outbound connection at a time to that target, and to two minutes between successive connections. If this is motivated by an outbound firewall rule it should be removed and the netadmin re-educated. Outbound port rules add nothing to firewall security. – user207421 Jun 06 '11 at 19:10
  • did you call `bind()` to set the src address before or after calling `connect()`? – Mike Pennington Jun 06 '11 at 20:39
  • First i did connect() before bind(), it was throwing exception, then i did the opposite, bind() then connect() and it worked but the client-side port is still allocated automatically. It is not the port i pass in the bind adress – wotan2009 Jun 07 '11 at 06:13
  • I think there are reasons for that. The source port is identification for TCP/IP stack to recognize which connection it is currently handling. When you did connect() to do job X, the stack assign you a port PPP, if then you bind this port successfully to do job Y, imagine there is an incoming connection looking for port PPP, how the stack suppose to know this connection is for job X or Y? Since it gonna be crazy to scan through the whole system for all the unavailable port (listening port), the system will allocate the source port for you and make sure it is unique. – Sany Liew Jan 30 '14 at 17:31

3 Answers3

1

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.

Brian White
  • 8,332
  • 2
  • 43
  • 67
0

Socket has multiple constructors. Try this one

qwerty
  • 3,801
  • 2
  • 28
  • 43
-1

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.

james_bond
  • 6,778
  • 3
  • 28
  • 34