java网络访问指定出口ip
Table of Contents
1 socket
可以在Socket构造函数中指定使用的本地ip,如:
Socket socket = new Socket("127.0.0.1", 12345, InetAddress.getByAddress(new byte[] {
new Integer(10).byteValue(),
new Integer(211).byteValue(),
new Integer(55).byteValue(),
new Integer(2).byteValue(),
}), 1234);
2 apache httpclient
通过HttpClient设置即可,如下:
byte b[] = new byte[4];
b[0] = new Integer(10).byteValue();
b[1] = new Integer(211).byteValue();
b[2] = new Integer(55).byteValue();
b[3] = new Integer(2).byteValue(); CloseableHttpResponse response = null;
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost:8080/TestServlet");
httpget.setConfig(RequestConfig.custom()
.setLocalAddress(InetAddress.getByAddress(b))
.build());