title: Java Socket, binding to local port
body: <p>I am trying to bind the Socket on the client side to any particular local port, in this code I used 20000.</p>
  
  <p>Normal connections such as below works just fine. But does not allow for me to choose the local port.</p>
  
  <pre><code>hostSocket = new Socket(host,80);
  </code></pre>
  
  <p>So I tried this: </p>
  
  <pre><code>hostSocket = new Socket(host, 80, InetAddress.getLocalHost(), 20000);
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>hostSocket = new Socket();
  hostSocket.bind(new InetSocketAddress("localhost", 20000));
  hostSocket.connect(new InetSocketAddress(host,80));
  </code></pre>
  
  <p>But they both leave me with this exception... in the second case the exception occurred on the connect call. I'm not really sure what I am missing and I would love some pointers. </p>
  
  <pre><code>java.net.SocketException: Invalid argument or cannot assign requested address
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:327)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:193)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
  at java.net.Socket.connect(Socket.java:546)
  at java.net.Socket.connect(Socket.java:495)
  at com.mb.proxy.netflix.NetflixPrefetchingAgent.connect(NetflixPrefetchingAgent.java:98)
  at com.mb.proxy.netflix.NetflixPrefetchingAgent.run(NetflixPrefetchingAgent.java:164)
  at java.lang.Thread.run(Thread.java:679)
  Exception in thread "Thread-19" java.lang.NullPointerException
  at com.mb.proxy.netflix.NetflixPrefetchingAgent.prefetchChunk(NetflixPrefetchingAgent.java:272)
  at com.mb.proxy.netflix.NetflixPrefetchingAgent.run(NetflixPrefetchingAgent.java:176)
  at java.lang.Thread.run(Thread.java:679)
  </code></pre>