Socket Proxy
How to connect a Socket server via HTTP proxy – Stack Overflow
I have a piece of code to connect to a Socket server, and it works fine.
Socket socket = new Socket();
nnect(new InetSocketAddress(address, port));
Now I want to connect via a HTTP proxy, what should I do?
I tried this and failed
SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(, addr);
Socket socket = new Socket(proxy);
this post suggests that I should use Jakarta Commons HttpClient, but how to use it to connect a Socket server via the HTTP proxy?
UPDATED:
I used SOCKS proxy and it doesn’t work, if I use HTTP proxy:
and it will throw an IllegalArgumentException
Proxy is null or invalid type
at
asked Aug 29 ’11 at 3:45
6
I’ve created small Socket Factory class to handle the HTTP CONNECT via socket. The socket then can be used as per-normal provided the proxy supports CONNECT to the destination.
public final class SocketFactory {
public static Socket GetSocket(String host, String port) throws IOException {
/*************************
* Get the jvm arguments
*************************/
int proxyPort = rseInt(tProperty(“oxyPort”));
String proxyHost = tProperty(“oxyHost”);
// Socket object connecting to proxy
Socket sock = new Socket(proxyHost, proxyPort);
/***********************************
* HTTP CONNECT protocol RFC 2616
***********************************/
String proxyConnect = “CONNECT ” + host + “:” + port;
// Add Proxy Authorization if proxyUser and proxyPass is set
try {
String proxyUserPass = (“%s:%s”,
tProperty(“oxyUser”),
tProperty(“oxyPass”));
(” HTTP/1. 0\nProxy-Authorization:Basic ”
+ (tBytes()));} catch (Exception e) {} finally {
(“\n\n”);}
tOutputStream()(tBytes());
/***********************************/
/***************************
* validate HTTP response.
***************************/
byte[] tmpBuffer = new byte[512];
InputStream socketInput = tInputStream();
int len = (tmpBuffer, 0, );
if (len == 0) {
throw new SocketException(“Invalid response from proxy”);}
String proxyResponse = new String(tmpBuffer, 0, len, “UTF-8”);
// Expecting HTTP/1. x 200 OK
if (dexOf(“200”)! = -1) {
// Flush any outstanding message in buffer
if (socketInput. available() > 0)
(socketInput. available());
// Proxy Connect Successful, return the socket for IO
return sock;} else {
throw new SocketFactoryException(“Fail to create Socket”,
proxyResponse);}}
/**
* Simplest Base64 Encoder adopted from GeorgeK
*
* @see */
private static class Base64 {
/***********************
* Base64 character set
***********************/
private final static char[] ALPHABET = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”. toCharArray();
* Translates the specified byte array into Base64 string.
* @param buf
* the byte array (not null)
* @return the translated Base64 string (not null)
*/
public static String encode(byte[] buf) {
int size =;
char[] ar = new char[((size + 2) / 3) * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = (i < size)? buf[i++]: 0;
byte b2 = (i < size)? buf[i++]: 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];}
switch (size% 3) {
case 1:
ar[–a] = ‘=’;
case 2:
ar[–a] = ‘=’;}
return new String(ar);}}}
answered Apr 8 ’13 at 1:10
Ernest NeoErnest Neo711 silver badge3 bronze badges
0
You could try JHttpTunnel, though you need software running on both sides of the tunnel for this to work.
answered Aug 29 ’11 at 4:11
prungeprunge21k3 gold badges72 silver badges75 bronze badges
2
This is from the link I posted previously:
SocketAddress addr = new InetSocketAddress(“”, 8080);
Remember, this new proxy object represents a proxy definition, nothing more. How do we use such an object? A new openConnection() method has been added to the URL class and takes a Proxy as an argument, it works the same way as openConnection() with no arguments, except it forces the connection to be established through the specified proxy, ignoring all other settings, including the system properties mentioned above.
So completing the previous example, we can now add:
URL url = new URL(“);
URLConnection conn = Connection(proxy);
This is from the link I posted earlier. I’m on the iPad so can’t format it properly.
Can you do it this way? I see you’re doing sockets directly but you’re doing so maybe do things this way?
answered Aug 29 ’11 at 5:53
1
Looks like you’re requesting a SOCKS proxy, which is different from an HTTP proxy. Perhaps try
Question: is your client HTTP based? I’m not sure this will work unless your client speaks HTTP.
answered Aug 29 ’11 at 4:02
Am I correct in saying that what you want is to use the proxy (for exemple squid) to establish a CONNECT method to a remote server (from rfc 2616)? Basically, the connection goes like this:
-open a socket to the proxy (host, port)
-send text to the proxy with basic header
NNECT HTTP/1. 0
Java Proxy Socket version 1. 0a
Basic YourBase64usernamePasswordIfRequired
-then, the proxy will return a status code (multiline text string) and the actual socket (if successfull)
-this is this socket that needs to be returned to the connection object
That could be done with personal classes but the beauty would be to reuse the proxy classes for it. This way, all the handshake with the proxy, especially the response code would be handled.
answered Sep 26 ’11 at 15:48
Well, you can manage the proxy by setting the requested url right after the proxy’s url, or using Java URL as following:
URL u = new URL(“”, ProxyHost, ProxyPort, destinationAddress);
By using this you build an URL like ProxyHost:ProxyPortdestinationAddress so you don’t have to set a Proxy class instance in Java that will likely throw the mentioned exception:
If you need to manage authentication settings you can always set the authenticator as default.
final String authUser = myAuthUser;
final String authPassword = myAuthPassword;
tDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authUser, CharArray());}});
Even though it’s a very “rudimental” way to set a proxy it’s very likely to work for HTTP Type Proxies if that’s the kind of proxy you have to set.
answered Mar 13 ’13 at 11:51
atzuatzu4233 silver badges14 bronze badges
As per Wikipedia on HTTP tunneling, the important thing about a HTTP proxy is that it proxies the HTTP protocol.
So if you have a server and a client and wish them to communicate through a HTTP proxy then both the server and client must be modified to communicate the HTTP protocol.
Alternatively you need additional software that can implement a VPN over HTTP, such as OpenVPN.
Edit: An exception is that some HTTP proxy servers support and have enabled a method called HTTP CONNECT which after a basic setup process over HTTP permits the creation and routing of a regular TCP socket. This permits connectivity to applications without the hard work of full conversion to HTTP tunneling. A good example of this is MSN Messenger. However as the Wikipedia articles notes this feature is often disabled, or not even supported for security reasons.
answered Aug 29 ’11 at 4:33
Steve-oSteve-o12. 4k2 gold badges39 silver badges57 bronze badges
4
I see its quite an old post, not sure if anybody is looking for this. For me the blow snippet is working perfectly fine.
Socket socketProxy = null;
if(tProperty(“oxyHost”)! = null) {
if(tProperty(“oxyUser”)! = null) {
String proxyUser = tProperty(“oxyUser”);
String proxyPassword = tProperty(“oxyPassword”);
//For Proxy Authentication
tDefault( new Authenticator() {
@Override public PasswordAuthentication getPasswordAuthentication() { return
new PasswordAuthentication(proxyUser, CharArray());}});
tProperty(“”, “”); // By default basic auth is disabled, by this basic auth is enabled}
Proxy proxy = new Proxy(, new InetSocketAddress(tProperty(“oxyHost”), rseInt(tProperty(“oxyPort”))));
socketProxy = new Socket(proxy);
InetSocketAddress address = eateUnresolved(host, port); // create a socket without resolving the target host to IP
nnect(address);}
One thing I notice from the original post is that the proxyAddr is not used. Not sure if it is typo in this post or a mistake.
SocketAddress **proxyAddr** = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(, **addr**);
answered Jun 2 at 2:51
I`m codding an app with c++ using Socks through Proxy, This tool help me a lot, have a look HERE
answered Feb 25 ’14 at 1:19
Zak ChapmanZak Chapman3593 silver badges8 bronze badges
Not the answer you’re looking for? Browse other questions tagged java sockets client or ask your own question.
Using NGINX as a WebSocket Proxy
The WebSocket protocol provides a way of creating web applications that support real‑time bidirectional communication between clients and servers. Part of HTML5, WebSocket makes it much easier to develop these types of applications than the methods previously available. Most modern browsers support WebSocket including Chrome, Firefox, Internet Explorer, Opera, and Safari, and more and more server application frameworks are now supporting WebSocket as well.
For enterprise production use, where multiple WebSocket servers are needed for performance and high availability, a load balancing layer that understands the WebSocket protocol is required, and NGINX has supported WebSocket since version 1. 3 and can act as a reverse proxy and do load balancing of WebSocket applications. (All releases of NGINX Plus also support WebSocket. )
Check out recent performance tests on the scalability of NGINX to load balance WebSocket connections.
The WebSocket protocol is different from the HTTP protocol, but the WebSocket handshake is compatible with HTTP, using the HTTP Upgrade facility to upgrade the connection from HTTP to WebSocket. This allows WebSocket applications to more easily fit into existing infrastructures. For example, WebSocket applications can use the standard HTTP ports 80 and 443, thus allowing the use of existing firewall rules.
A WebSocket application keeps a long‑running connection open between the client and the server, facilitating the development of real‑time applications. The HTTP Upgrade mechanism used to upgrade the connection from HTTP to WebSocket uses the Upgrade and Connection headers. There are some challenges that a reverse proxy server faces in supporting WebSocket. One is that WebSocket is a hop‑by‑hop protocol, so when a proxy server intercepts an Upgrade request from a client it needs to send its own Upgrade request to the backend server, including the appropriate headers. Also, since WebSocket connections are long lived, as opposed to the typical short‑lived connections used by HTTP, the reverse proxy needs to allow these connections to remain open, rather than closing them because they seem to be idle.
NGINX supports WebSocket by allowing a tunnel to be set up between a client and a backend server. For NGINX to send the Upgrade request from the client to the backend server, the Upgrade and Connection headers must be set explicitly, as in this example:
location /wsapp/ {
proxy_pass wsbackend;
proxy__version 1. 1;
proxy_set_header Upgrade $_upgrade;
proxy_set_header Connection “Upgrade”;
proxy_set_header Host $host;}
Once this is done, NGINX deals with this as a WebSocket connection.
NGINX WebSocket Example
Here is a live example to show NGINX working as a WebSocket proxy. This example uses ws, a WebSocket implementation built on NGINX acts as a reverse proxy for a simple WebSocket application utilizing ws and These instructions have been tested with Ubuntu 13. 10 and CentOS 6. 5 but might need to be adjusted for other OSs and versions. For this example, the WebSocket server’s IP address is 192. 168. 100. 10 and the NGINX server’s IP address is 192. 20.
If you don’t already have and npm installed, run the following command:
For Debian and Ubuntu:
$ sudo apt-get install nodejs npm
For RHEL and CentOS:
$ sudo yum install nodejs npm
is installed as nodejs on Ubuntu and as node on CentOS. The example uses node, so on Ubuntu we need to create a symbolic link from nodejs to node:
$ ln -s /usr/bin/nodejs /usr/local/bin/node
To install ws, run the following command:
$ sudo npm install ws
Note: If you get the error message: “Error: failed to fetch from registry: ws”, run the following command to fix the problem:
$ sudo npm config set registry Then run the sudo npm install ws command again.
ws comes with the program /root/node_modules/ws/bin/wscat that we will use for our client, but we need to create a program to act as the server. Create a file called with these contents:
(“Server started”);
var Msg = ”;
var WebSocketServer = require(‘ws’), wss = new WebSocketServer({port: 8010});
(‘connection’, function(ws) {
(‘message’, function(message) {
(‘Received from client:%s’, message);
(‘Server received from client: ‘ + message);});});
To execute the server program, run the following command:
$ node
The server prints an initial “Server started” message and then listens on port 8010, waiting for a client to connect to it. When it receives a client request, it echoes it and sends a message back to the client containing the message it received. To have NGINX proxy these requests, we create the following configuration. We’re adding the map block so that the Connection header is correctly set to close when the Upgrade header in the request is set to ”.
{
map $_upgrade $connection_upgrade {
default upgrade;
” close;}
upstream websocket {
server 192. 10:8010;}
server {
listen 8020;
location / {
proxy_pass websocket;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;}}}
NGINX listens on port 8020 and proxies requests to the backend WebSocket server. The proxy_set_header directives enable NGINX to properly handle the WebSocket protocol.
To test the server, we run wscat as our client:
$ /root/node_modules/ws/bin/wscat –connect ws192. 20:8020
wscat connects to the WebSocket server through the NGINX proxy. When you type a message for wscat to send to the server, you see it echoed on the server and then a message from the server appears on the client. Here’s a sample interaction:
Server:
Client:
Server started
wscat –connect ws192. 20:8020
Connected (press CTRL+C to quit)
> Hello
Received from client: Hello
< Server received from client: Hello
Here we see that the client and server are able to communicate through NGINX which is acting as a proxy and messages can continue to be sent back and forth until either the client or server disconnects. All that is needed to get NGINX to properly handle WebSocket is to set the headers correctly to handle the Upgrade request that upgrades the connection from HTTP to WebSocket.
Further Reading
WebSocket proxying at
NGINX and NGINX Plus feature comparison
NGINX Plus Technical Specifications
SOCKS Proxy Primer: What Is SOCKs5 and Why Should You …
co-authored by Darshan S. Mulimath, Megha B. Sasidhar, and Ashiq Khader
In computer networks, a proxy or proxy server is a computer that sits between you and the server. It acts as a gateway between a local network and a large-scale network, such as the internet.
A proxy server works by intercepting connections between sender and receiver. All incoming data enters through one port and is forwarded to the rest of the network via another port.
Aside from traffic forwarding, proxy servers provide security by hiding the actual IP address of a server. They also have caching mechanisms that store requested resources to improve performance. A proxy server can encrypt your data so it is unreadable in transit and block access to certain webpages based on IP address.
Now that we have a general sense of how a proxy works, let’s zoom in on a specific type of proxy — SOCKS — and, specifically, the SOCKs5 variant.
What Is a SOCKS Proxy?
SOCKS, which stands for Socket Secure, is a network protocol that facilitates communication with servers through a firewall by routing network traffic to the actual server on behalf of a client. SOCKS is designed to route any type of traffic generated by any protocol or program.
A SOCKS proxy server creates a Transmission Control Protocol (TCP) connection to another server behind the firewall on the client’s behalf, then exchanges network packets between the client and the actual server. The SOCKS proxy server doesn’t interpret the network traffic between client and server in any way; it is often used because clients are behind a firewall and are not permitted to establish TCP connections to outside servers unless they do it through the SOCKS proxy server. Therefore, a SOCKS proxy relays a user’s TCP and User Datagram Protocol (UDP) session over firewall.
SOCKS is a layer 5 protocol, and it doesn’t care about anything below that layer in the Open Systems Interconnection (OSI) model — meaning you can’t use it to tunnel protocols operating below layer 5. This includes things such as ping, Address Resolution Protocol (ARP), etc. From a security perspective, it won’t allow an attacker to perform scans using tools such as Nmap if they are scanning based on half-open connections because it works at layer 5.
Since SOCKS sits at layer 5, between SSL (layer 7) and TCP/UDP (layer 4), it can handle several request types, including HTTP, HTTPS, POP3, SMTP and FTP. As a result, SOCKS can be used for email, web browsing, peer-to-peer sharing, file transfers and more.
Other proxies built for specific protocols at layer 7, such as an HTTP proxy that is used to interpret and forward HTTP or HTTPS traffic between client and server, are often referred to as application proxies.
There are only two versions: SOCKS4 and SOCKs5. The main differences between SOCKs5 and SOCKS4 are:
SOCKS4 doesn’t support authentication, while SOCKs5 supports a variety of authentication methods; and
SOCKS4 doesn’t support UDP proxies, while SOCKs5 does.
A SOCKs5 proxy is more secure because it establishes a full TCP connection with authentication and uses the Secure Shell (SSH) encrypted tunneling method to relay the traffic.
Why You Should Adopt SOCKs5
Below are four key benefits to using a SOCKs5 proxy with SSH tunneling.
1. Access Back-End Services Behind a Firewall
Usually, a cluster is hosted in the cloud behind a firewall to minimize potential security vulnerabilities. There are two ways to access any backend services that are running inside a cluster, and each has its limitations:
Expose backend services to public (and accept the associated security risk); or
Whitelist the client or user’s IP to allow traffic to backend services (this is not the right solution for when a user’s IP changes, however).
A SOCKs5 proxy with dynamic port forwarding using SSH can be an alternative to the two undesirable options above. An administrator or developer could access any backend services within a cluster that is hosted in the cloud behind a firewall for debugging, monitoring and administrating from a public network without exposing the backend service ports or whitelisting specific IPs.
Let’s look at a use case. For security reasons, the administration or monitoring application APIs or web user interface (UI) ports for monitoring Hadoop cluster are closed by default when hosted on the cloud. To access these APIs or web UIs, you can use SSH dynamic port forwarding to master or edge a node cluster, since the master node will have a public IP and run SSH services by default, which is exposed so the user can connect from outside.
For another example, say you’re working with a virtual private cloud (VPC). You can deploy a bastion host to securely access remote instances within a VPC by limiting their access to the outside world. You can access the bastion host from the outside world, and only port 22 (SSH) is opened. Using SSH dynamic port forwarding (SOCKs5 proxy), you can access the remote instances that are running in the VPC.
2. No Special Setup Required
SOCKs5 doesn’t require special setup, as long as you have SSH access to either the Edge node or gateway of a cluster. Therefore, users such as administrators and developers can access back-end resources behind the firewall using an SSH tunnel without requiring a virtual private network (VPN).
3. No Third-Party Public or Free Proxy Server in Your Deployments
Since a SOCKs5 proxy routes all kinds of TCP and UDP traffic to their respective service through SSH tunneling, no layer 7 application-related special proxies are required for each service to route application requests.
4. Fewer Errors, Better Performance
Unlike other application proxies, SOCKs5 does not rewrite data packets. It just relays the traffic between devices. Therefore, it is less prone to errors, and performance increases automatically.
How Does SOCKs5 Work in Practice?
Any CISO wouldn’t jump at the chance to embrace the benefits listed above. But what does a SOCKs5 proxy look like in the context of an enterprise security strategy? Where do security leaders begin when implementing SOCKs5 in their environment? Below are some key steps to help you get started.
Setting Up a SOCKs5 Proxy Connection
To SOCKSify an IT environment, the client application must have the capacity to support the SOCKs5 protocol. The syntax below is based on the SSH client on Linux; it shows how to create a SOCKs5 proxy server running on your local computer and then authenticate to the Edge node of a cluster or gateway hosted on cloud that routes traffic to the servers inside the cluster:
$ ssh -D 30001 [email protected] -C -f -N (password: xyz; or
$ ssh -i /path/to/private_key -D 30001 [email protected] -C -f -N
The above command starts the SOCKs5 server and binds to port 30001, then connects to Edge Node, Master Node or Gateway Node over the SSH tunnel hosted on the cloud.
The options used in the above command do the following:
D 30001 tells SSH to create a SOCKs5 server on port 30001 on the client computer.
C compresses data before sending.
N means “Do not execute a remote command. ” This is useful for simply forwarding ports (protocol version 2 only).
F requests SSH to go to the background just before command execution.
Accessing the Endpoints Using the SOCKs5 Protocol
Once a SOCKs5 proxy is created, configure your clients to access the internal services of the cluster. To keep it simple, we use a command line URL (cURL) that supports the SOCKs5 protocol. Other methods such as using a web browser require some additional setup and configurations.
The below cURL command shows how to access one of the HTTPS application endpoints listening on port 8000 behind a firewall using the SOCKs5 proxy over the SSH tunnel created above:
curl -x socks5hlocalhost:30001 -v -k -X GET EdgeNodeSSHserverIP:8000
The above cURL tool connects to port 30001 on localhost. Upon receiving a HTTP GET request on port 30001 from the cURL, the SSH client sends the same request via SSH tunnel to the SSH server.
The remote SSH server handles the request and passes the request to a back-end service listening at port 8000. The response is sent back to the client over the same SSH tunnel to the client’s SOCKs5 proxy. The proxy relays the response to the cURL, which displays the response.
Once you have created a SOCKs5 proxy using the SSH dynamic port forwarding method, you can also use the netcat utility to test the TCP connection. As shown below, a TCP connection test is made for back-end services listening at port 8443 with the SOCKs5 proxy:
ncat –proxy 127. 0. 1:30001 –proxy-type socks5 EdgeNodeSSHserverIP 8443 -nv
In Summary
A SOCKs5 proxy is a lightweight, general-purpose proxy that sits at layer 5 of the OSI model and uses a tunneling method. It supports various types of traffic generated by protocols, such as HTTP, SMTP and FTP. SOCKs5 is faster than a VPN and easy to use. Since the proxy uses a tunneling method, public cloud users can access resources behind the firewall using SOCKs5 over a secured tunnel such as SSH.
Frequently Asked Questions about socket proxy
What is WebSocket proxy?
reverse proxy server, WebSocket. The WebSocket protocol provides a way of creating web applications that support real‑time bidirectional communication between clients and servers. Part of HTML5, WebSocket makes it much easier to develop these types of applications than the methods previously available.May 16, 2014
What does SOCKS5 proxy do?
A SOCKs5 proxy is a lightweight, general-purpose proxy that sits at layer 5 of the OSI model and uses a tunneling method. It supports various types of traffic generated by protocols, such as HTTP, SMTP and FTP. SOCKs5 is faster than a VPN and easy to use.Sep 27, 2019
Do proxies support Websockets?
Today, most transparent proxy servers will not yet be familiar with the Web Socket protocol and these proxy servers will be unable to support the Web Socket protocol. In the future, however, proxy servers will likely become Web Sockets-aware and able to properly handle and forward WebSocket traffic.Mar 16, 2010