Endpoints and Ports
By default, the server will listen on port 8080 for incoming IPv4 or IPv6 connections on
any interface. To simply change the port the server will listen on, you can use
the port() directive of the host. Please note, that hosting a server on ports below 1024
will require additional permissions on some operating systems.
val app = Layout.create()
val host = Host.create()
.handler(app)
.port(80)To configure the server to listen on specific interfaces only, you can bind() those
endpoints explicitly. As soon as an endpoint is bound, the port set via port() is ignored.
import org.genhttp.engine.internal.Host
import org.genhttp.modules.layouting.Layout
import java.net.InetAddress
suspend fun main() {
val app = Layout.create()
Host.create()
.handler(app)
.bind(InetAddress.getByName("192.168.2.10"), 8888)
.bind(InetAddress.getByName("fd00::10"), 8888)
.run()
}By default, the server will try to listen to both incoming IPv4 as well as IPv6 connections (even
if you specify an IPv4 or IPv6 address manually). To disable this behavior, specify dualStack = false.
The following example will listen to any incoming IPv4 request on any IP address:
import org.genhttp.engine.internal.Host
import org.genhttp.modules.layouting.Layout
import java.net.InetAddress
suspend fun main() {
val app = Layout.create()
Host.create()
.handler(app)
.bind(InetAddress.getByName("0.0.0.0"), 8080, dualStack = false)
.run()
}If the server cannot bind to an endpoint, e.g. because the port is already in use, start() fails with
a BindingException (and run() logs the error and returns -1).
The JDK cannot open IPv6-only sockets. An IPv6 endpoint with dualStack = false (including null
for any address) therefore accepts IPv4 connections on the TCP level, but closes them right away.
Secure Endpoints
The bind() overload that accepts a CertificateProvider (see
SSL Endpoints) also takes an sslProtocols argument to restrict which TLS versions the
endpoint accepts, defaulting to TLS 1.2 and TLS 1.3:
import org.genhttp.api.infrastructure.CertificateProvider
import org.genhttp.api.infrastructure.SslProtocol
import org.genhttp.engine.internal.Host
import org.genhttp.modules.layouting.Layout
import java.security.KeyStore
// see "SSL Endpoints" for how to load a certificate
suspend fun serve(certificate: KeyStore.PrivateKeyEntry) {
val app = Layout.create()
Host.create()
.handler(app)
.bind(null, 443, CertificateProvider.from(certificate), sslProtocols = setOf(SslProtocol.Tls13))
.run()
}The versions are passed as a set of SslProtocol values (Tls12, Tls13), which stands in for
the SslProtocols flags of GenHTTP.