Set Specify Local IP Address

 

Socket

   1: Socket socket = new Socket();

   2:  

   3: // If set the port zero, the port will set any available port in you system

   4: SocketAddress localAddress = new InetSocketAddress(addr, 0);

   5:  

   6: socket.bind(localAddress);

   7:  

   8: SocketAddress remoteAddress = new InetSocketAddress(user.getIpAddress(), 8000);

   9:  

  10: // set Connection Timeout 

  11: socket.connect(remoteAddress, 2000);

 

URLConnection

   1: URL url = new URL(pushURL);

   2:             

   3: // set up specify local IP Address

   4: SocketAddress localAddress = new InetSocketAddress(addr, 0);

   5: Proxy proxy = new Proxy(Proxy.Type.DIRECT, localAddress);

   6: URLConnection urlConnection = url.openConnection(proxy);

   7:  

   8: // set the timeout

   9: urlConnection.setConnectTimeout(2000);

  10: urlConnection.setReadTimeout(2000);

 

 

HttpClient

   1: HttpClient client = new DefaultHttpClient();

   2: client.getParams().setParameter("http.connection.timeout", 1000);

   3: client.getParams().setParameter("http.socket.timeout", 1000);

   4: client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);

   5: client.getConnectionManager().closeIdleConnections(2000, TimeUnit.MILLISECONDS);

   6:  

   7: // Set specify local ip address

   8: client.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, addr); 

   9: post.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, addr);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s