Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Last active October 7, 2018 15:15
Show Gist options
  • Save swankjesse/7ffbc7f7ec9d6fc9deb026d8726eae84 to your computer and use it in GitHub Desktop.
Save swankjesse/7ffbc7f7ec9d6fc9deb026d8726eae84 to your computer and use it in GitHub Desktop.
package okhttp3;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.net.SocketFactory;
public class UnixSocketFactory extends SocketFactory implements Dns {
private final Map<String, String> pathToHostname = new LinkedHashMap<>();
private final Map<String, String> hostnameToPath = new LinkedHashMap<>();
private int nextId = 1;
public HttpUrl urlForPath(String path) {
return new HttpUrl.Builder()
.scheme("http")
.host(hostnameForPath(path))
.build();
}
private synchronized String hostnameForPath(String path) {
String hostname = pathToHostname.get(path);
if (hostname == null) {
hostname = "p" + (nextId++) + ".socket";
pathToHostname.put(path, hostname);
hostnameToPath.put(hostname, path);
}
return hostname;
}
private synchronized String pathForInetAddress(InetAddress inetAddress) {
return hostnameToPath.get(inetAddress.getHostName());
}
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
return hostname.endsWith(".socket")
? Arrays.asList(InetAddress.getByAddress(hostname, new byte[] {0, 0, 0, 0}))
: Dns.SYSTEM.lookup(hostname);
}
@Override public Socket createSocket() throws IOException {
return new UnixSocket();
}
class UnixSocket extends Socket {
@Override public void connect(SocketAddress endpoint, int timeout) throws IOException {
String path = pathForInetAddress(((InetSocketAddress) endpoint).getAddress());
System.out.println(path);
}
}
@Override public Socket createSocket(InetAddress inetAddress, int i) {
throw new UnsupportedOperationException();
}
@Override public Socket createSocket(String s, int i) {
throw new UnsupportedOperationException();
}
@Override public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) {
throw new UnsupportedOperationException();
}
@Override
public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) {
throw new UnsupportedOperationException();
}
}
@swankjesse
Copy link
Author

Alternately, instead of using a map to track the hostname and path, you could just hex encode the path string. That makes this stateless, which is nice. But it imposes a limit on the length of the path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment