Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify which network interface OkHttp will use when establishing new connections

Tags:

java

okhttp

I am using OkHttp within an application I run on a server, and the server has multiple network interfaces configured at the OS level.

How I can control which network interface OkHttp will to use to send new requests?

By default, I see it simply selects one of the interfaces available, where as I would like to provide users of my application built on top of OkHttp the ability to configure the interface which should be used.

like image 946
mitaichik Avatar asked Oct 28 '25 03:10

mitaichik


1 Answers

I believe you can use

https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#socketFactory-javax.net.SocketFactory-

public OkHttpClient.Builder socketFactory(SocketFactory socketFactory)

Sets the socket factory used to create connections. OkHttp only uses the parameterless createSocket() method to create unconnected sockets. Overriding this method, e. g., allows the socket to be bound to a specific local address. If unset, the system-wide default socket factory will be used.

For example https://github.com/yschimke/okurl/blob/e307022667e2beb474309af5b350cd241f2a9045/src/main/kotlin/com/baulsupp/okurl/network/InterfaceSocketFactory.kt

class InterfaceSocketFactory(private val localAddress: InetAddress) : SocketFactory() {
  private val systemFactory = getDefault()

  override fun createSocket(): Socket {
    val s = systemFactory.createSocket()
    s.bind(InetSocketAddress(localAddress, 0))
    return s
  }
like image 52
Yuri Schimke Avatar answered Oct 30 '25 03:10

Yuri Schimke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!