Skip to content

Instantly share code, notes, and snippets.

@jannson
Forked from swankjesse/UnixSocketFactory.java
Created October 7, 2018 15:15
Show Gist options
  • Save jannson/4c55af318dfde57380938731a6267222 to your computer and use it in GitHub Desktop.
Save jannson/4c55af318dfde57380938731a6267222 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment