10 Java Networking

The Java networking API provides classes for networking functionality, including addressing, classes for using URLs and URIs, socket classes for connecting to servers, networking security functionality, and more. It consists of these packages and modules:

  • java.net: Classes for implementing networking applications.
  • java.net.http: Contains the API for the HTTP Client, which provides high-level client interfaces to HTTP (versions 1.1 and 2) and low-level client interfaces to WebSocket instances. See Java HTTP Client for more information about this API, including videos and sample code.

    Note:

    You can use the jwebserver tool for testing and debugging your client application.
  • javax.net: Classes for creating sockets.
  • javax.net.ssl: Secure socket classes.
  • jdk.httpserver: Platform-specific APIs for building HTTP servers for educational and testing purposes, as well as the jwebserver tool for running a minimal HTTP server.
  • jdk.net: Platform-specific socket options for the java.net and java.nio.channels socket classes.

Networking System Properties

You can set the following networking system properties in one of three ways:

  • Using the -D option of the java command
  • Using the System.setProperty(String, String) method
  • Specifying them in the $JAVA_HOME/conf/net.properties file. Note that you can specify only proxy-related properties in this file.

Unless specified otherwise, a property value is checked every time it's used.

See Networking Properties and the java.net.http module in the Java SE API Specification for more information.

HTTP Client Properties

Some of the following properties are subject to predefined minimum and maximum values that override any user-specified values. Note that the default value of boolean values is true if the property exists but has no value.

Table 10-1 HTTP Client Properties

Property Default Value Description
jdk.httpclient.allowRestrictedHeaders No default value

A comma-separated list of normally restricted HTTP header names that users may set in HTTP requests or by user code in HttpRequest instances.

By default, user code cannot set the following request headers: connection, content-length, expect, host, and upgrade. You can override this behavior with this property.

Header names specified in this property are case-insensitive, and whitespace is ignored. Note that this property is intended for testing and not for real-world deployments. Protocol errors or other undefined behavior are likely to occur when using this property.

There may be other headers that are restricted from being set depending on the context. This includes the Authorization header when the relevant HttpClient has an authenticator set. These restrictions cannot be overridden by this property.

jdk.httpclient.auth.retrylimit 3 The number of attempts the Basic authentication filter will attempt to retry a failed authentication.
jdk.httpclient.bufsize

16384 (16 kB)

The size to use for internal allocated buffers in bytes.
jdk.httpclient.connectionPoolSize 0 The maximum number of connections to keep in the HTTP/1.1 keep alive cache. A value of 0 means that the cache is unbounded.
jdk.httpclient.connectionWindowSize 2^26

The HTTP/2 client connection window size in bytes.

The maximum size is 2^31-1. This value cannot be smaller than the stream window size.

jdk.httpclient.disableRetryConnect false Whether automatic retry of connection failures is disabled. If false, then retries are attempted (subject to the retry limit).
jdk.httpclient.enableAllMethodRetry false Whether it is permitted to automatically retry non-idempotent HTTP requests.
jdk.httpclient.enablepush 1 Whether HTTP/2 push promise is enabled. A value of 1 enables push promise; a value of 0 disables it.
jdk.httpclient.hpack.maxheadertablesize

16384 (16 kB)

The HTTP/2 client maximum HPACK header table size in bytes.
jdk.httpclient.HttpClient.log No default value

Enables high-level logging of various events through the Java Logging API (which is contained in the package java.util.logging).

The value contains a comma-separated list of any of the following items:

  • errors
  • requests
  • headers
  • content
  • frames
  • ssl
  • trace
  • channel

You can append the frames item with a colon-separated list of any of the following items:

  • control
  • data
  • window
  • all

Specifying an item adds it to the HTTP client's log. For example, if you specify the following value, then the Java Logging API logs all possible HTTP Client events:

errors,requests,headers,frames:control:data:window,ssl,trace,channel

Note that you can replace control:data:window with all.

The name of the logger is jdk.httpclient.HttpClient, and all logging is at level INFO.

jdk.httpclient.keepalive.timeout 30 The number of seconds to keep idle HTTP/1.1 connections alive in the keep alive cache.
jdk.httpclient.keepalive.timeout.h2 See the description The number of seconds to keep idle HTTP/2 connections alive. If not set, then the jdk.httpclient.keepalive.timeout setting is used.
jdk.httpclient.maxframesize

16384 (16 kB)

The HTTP/2 client maximum frame size in bytes. The server is not permitted to send a frame larger than this.
jdk.httpclient.maxstreams 100 The maximum number of concurrent HTTP/2 streams per connection.
jdk.httpclient.receiveBufferSize The operating system's default value The HTTP client socket receive buffer size in bytes. See StandardSocketOptions.SO_RCVBUF.
jdk.httpclient.redirects.retrylimit 5 The maximum number of attempts to send a HTTP request when redirected or any failure occurs for any reason.
jdk.httpclient.sendBufferSize Operating system default The HTTP client socket send buffer size. See StandardSocketOptions.SO_SNDBUF. Values less than or equal to zero are ignored.
jdk.httpclient.websocket.writeBufferSize 16384 (16 kB) The buffer size used by the web socket implementation for socket writes.
jdk.httpclient.windowsize

16777216 (16 MB)

The HTTP/2 client stream window size in bytes.
jdk.internal.httpclient.disableHostnameVerification false If true (or set to an empty string), hostname verification in SSL certificates is disabled. This is a system property only and not available in conf/net.properties. It is provided for testing purposes only.

Note:

The properties jdk.http.auth.proxying.disabledSchemes and jdk.http.auth.tunneling.disabledSchemes, described in Other Proxy-Related Properties, are also taken into account by HttpClient.

IPv4 and IPv6 Protocol Properties

These two properties are checked only once, at startup.

Table 10-2 IPv4 and IPv6 Protocol Properties

Property Default Value Description
java.net.preferIPv4Stack false

If IPv6 is available on the operating system, then the underlying native socket will be, by default, an IPv6 socket, which lets applications connect to, and accept connections from, both IPv4 and IPv6 hosts.

Set this property to true if you want your application use IPv4-only sockets. This implies that it won't be possible for the application to communicate with IPv6-only hosts.

java.net.preferIPv6Addresses false

When dealing with a host which has both IPv4 and IPv6 addresses, and if IPv6 is available on the operating system, the default behavior is to prefer using IPv4 addresses over IPv6 ones. This is to ensure backward compatibility, for example, for applications that depend on the representation of an IPv4 address (such as 192.168.1.1).

Set this property to true to change this preference and use IPv6 addresses over IPv4 ones where possible.

Set this property to system to preserve the order of the addresses as returned by the operating system.

HTTP Proxy Properties

The following proxy settings are used by the HTTP protocol handler and the default proxy selector.

Table 10-3 HTTP Proxy Properties

Property Default Value Description
http.proxyHost No default value Proxy server that the HTTP protocol handler will use.
http.proxyPort 80 Port that the HTTP protocol handler will use.
http.nonProxyHosts localhost|127.*|[::1]

Indicates the hosts that should be accessed without going through the proxy. Typically, this defines internal hosts. The value of this property is a list of hosts, separated by the vertical bar (|) character. In addition, you can use the asterisk (*) for pattern matching. For example, the following specifies that every host in the exmaple.com domain and localhost should be accessed directly even if a proxy server is specified:

-Dhttp.nonProxyHosts="*.example.com|localhost"

The default value excludes all common variations of the loopback address.

HTTPS Proxy Properties

HTTPS, HTTP over SSL, is a secure version of HTTP mainly used when confidentiality is needed (such as payment web sites). The following proxy settings are used by the HTTPS protocol handler and the default proxy selector.

Note:

The HTTPS protocol handler uses the same http.nonProxyHosts property as the HTTP protocol.

Table 10-4 HTTPS Proxy Properties

Property Default Value Description
https.proxyHost No default value Proxy server that the HTTPS protocol handler will use.
https.proxyPort 443 Port that the HTTPS protocol handler will use.

FTP Proxy Properties

The following proxy settings are used by the FTP protocol handler.

Table 10-5 FTP Proxy Properties

System Property Default Value Description
ftp.proxyHost No default value Proxy server that the FTP protocol handler will use.
ftp.proxyPort 80 Port that the FTP protocol handler will use.
ftp.nonProxyHosts localhost|127.*|[::1]

Similar to http.nonProxyHosts, this property indicates the hosts that should be accessed without going through the proxy. Typically, this defines internal hosts. The value of this property is a list of hosts, separated by the vertical bar (|) character. In addition, you can use the asterisk (*) for pattern matching. For example, the following specifies that every host in the exmaple.com domain and localhost should be accessed directly even if a proxy server is specified:

-Dftp.nonProxyHosts="*.example.com|localhost"

The default value excludes all common variations of the loopback address.

SOCKS Proxy Properties

The SOCKS proxy enables a lower-level type of tunneling because it works at the TCP level. Specifying a SOCKS proxy server results in all TCP connections going through that proxy server unless other proxies are specified. The following proxy settings are used by the SOCKS protocol handler.

Table 10-6 SOCKS Proxy Properties

Property Default Value Description
java.net.socks.username No default value See Acquiring the SOCKS User Name and Password
java.net.socks.password No default value See Acquiring the SOCKS User Name and Password
socksProxyHost No default value SOCKS proxy server that the SOCKS protocol handler will use.
socksProxyPort 1080 Port that the SOCKS protocol handler will use.
socksProxyVersion 5 The version of the SOCKS protocol supported by the server. The default is 5 indicating SOCKS V5; alternatively 4 can be specified for SOCKS V4. Setting the property to values other than these leads to unspecified behavior.
Acquiring the SOCKS User Name and Password

The SOCKS user name and password are acquired in the following way:

  1. First, if the application has registered a java.net.Authenticator default instance, then this will be queried with the protocol set to the string SOCKS5, and the prompt set to the string SOCKS authentication.
  2. If the authenticator does not return a user name/password or if no authenticator is registered, then the system checks the values of properties java.net.socks.username and java.net.socks.password.
  3. If these values don't exist, then the system property user.name is checked for a user name. In this case, no password is supplied.

Other Proxy-Related Properties

Table 10-7 Other Proxy-Related Properties

Property Default Value Description
jdk.http.auth.proxying.disabledSchemes See conf/net.properties

Lists the authentication schemes that will be disabled when proxying HTTP.

The value of this property is a comma-separated list of case-insensitive authentication scheme names, as defined by their relevant RFCs. Schemes include Basic, Digest, NTLM, Kerberos, and Negotiate. A scheme that is not known or supported is ignored.

In some environments, certain authentication schemes may be undesirable when proxying HTTP or HTTPS. For example, Basic results in effectively the cleartext transmission of the user's password over the physical network.

jdk.http.auth.tunneling.disabledSchemes See conf/net.properties

Lists the authentication schemes that will be disabled when tunneling HTTPS over a proxy with the HTTP CONNECT method.

The value of this property is a comma-separated list of case-insensitive authentication scheme names, as defined by their relevant RFCs. Schemes include Basic, Digest, NTLM, Kerberos, and Negotiate. A scheme that is not known or supported is ignored.

java.net.useSystemProxies false

If true, then the operating system's proxy settings are used.

Note that the system properties that explicitly set proxies like http.proxyHost take precedence over the system settings even if java.net.useSystemProxies is set to true.

This property is checked only once, at startup.

UNIX Domain Sockets Properties

Calling ServerSocketChannel.bind with a null address parameter will bind the channel's socket to an automatically assigned socket address. For UNIX domain sockets, this means a unique path in some predefined system temporary directory.

Use these properties to control the selection of this directory:

Table 10-8 UNIX Doman Sockets Properties

Property Default Value Description
java.io.tmpdir Dependent on the operating system If the temporary directory can't be determined with the jdk.net.unixdomain.tmpdir system property, then the directory specified by the java.io.tmpdir system property is used.
jdk.net.unixdomain.tmpdir On some platforms, (for example, some UNIX systems) this will have a predefined default value. On others, (for example, Windows) there is no default value. Specifies the directory to use for automatically bound server socket addresses.

On Linux and macOS, the search order to determine this directory is as follows:

  1. The system property jdk.net.unixdomain.tmpdir (set on the command line or by System.setProperty(String, String))
  2. The same property set in the $JAVA_HOME/conf/net.properties file
  3. The system property java.io.tmpdir

On Windows, the search order to determine this directory is as follows:

  1. The system property jdk.net.unixdomain.tmpdir (set on the command line or by System.setProperty(String, String))
  2. The same property set in the %JAVA_HOME%\conf\net.properties file
  3. The TEMP environment variable
  4. The system property java.io.tmpdir

Because UNIX domain socket addresses are limited in length to approximately 100 bytes (depending on the platform), it is important to ensure that the temporary directory's name together with the file name used for the socket does not exceed this limit.

Note:

If a client socket is connected to a remote destination without calling bind first, then the socket is implicitly bound. In this case, UNIX domain sockets are unnamed (that is, their path is empty). This behavior is not affected by any system or networking properties.

Other HTTP URL Stream Protocol Handler Properties

These properties are checked only once, at startup.

Table 10-9 Other HTTP URL Stream Protocol Handler Properties

Property Default Value Description
http.agent Java/<version> Defines the string sent in the User-Agent request header in HTTP requests. Note that the string Java/<version> will be appended to the one provided in the property.

For example, if -Dhttp.agent="example" is specified, the User-Agent header will contain example Java/1.8.0 if the version of the JVM is 1.8.0).

http.auth.digest.cnonceRepeat 5 See System Properties That Modify the Behavior of HTTP Digest Authentication Mechanism.
http.auth.digest.reEnabledAlgorithms No default value By default, certain message digest algorithms are disabled for use in HTTP Digest authentication due to their proven security limitations. This only applies to proxy authentication and plain-text HTTP server authentication. Disabled algorithms are still usable for HTTPS server authentication. The default list of disabled algorithms is specified in the java.security properties file and currently comprises MD5 and SHA-1. If it is still required to use one of these algorithms, then they can be re-enabled by setting this property to a comma-separated list of the algorithm names.
http.auth.digest.validateProxy false See System Properties That Modify the Behavior of HTTP Digest Authentication Mechanism.
http.auth.digest.validateServer false See System Properties That Modify the Behavior of HTTP Digest Authentication Mechanism.
http.auth.ntlm.domain No default value

Similar to other HTTP authentication schemes, New Technology LAN Manager (NTLM) uses the java.net.Authenticator class to acquire user names and passwords when they are needed. However, NTLM also needs the NT domain name. There are three options for specifying the domain:

  1. Do not specify it. In some environments, the domain is not actually required and the application does not have to specify it.
  2. The domain name can be encoded within the user name by prefixing the domain name followed by a backslash (\) before the user name. With this method, existing applications that use the Authenticator class do not need to be modified, as long as users are made aware that this notation must be used.
  3. If a domain name is not specified as in the second option and the system property http.auth.ntlm.domain is defined, then the value of this property will be used as the domain name.
http.keepAlive true

Indicates if persistent (keep-alive) connections should be supported. They improve performance by allowing the underlying socket connection to be reused for multiple HTTP requests. If this is set to true, then persistent connections will be requested with HTTP 1.1 servers.

Set this property to false to disable the use of persistent connections.

http.KeepAlive.queuedConnections 10 The maximum number of keep-alive connections to be on the queue for clean up.
http.KeepAlive.remainingData 512 The maximum amount of data in kilobytes that will be cleaned off the underlying socket so that it can be reused.
http.keepAlive.time.server and http.keepAlive.time.proxy 5 These properties modify the behavior of the HTTP keepalive cache in the case where the server (or proxy) has not specified a keepalive time. If the property is set in this case, then idle connections will be closed after the specified number of seconds. If the property is set, and the server does specify a keepalive time in a "Keep-Alive" response header, then the time specified by the server is used. If the property is not set and also the server does not specify a keepalive time, then connections are kept alive for an implementation defined time, assuming http.keepAlive is true.
http.maxConnections 5 If HTTP persistent connections (see the http.keepAlive property) are enabled, then this value determines the maximum number of idle connections that will be simultaneously kept alive per destination.
http.maxRedirects 20 Integer value that determines the maximum number, for a given request, of HTTP redirects that will be automatically followed by the protocol handler.
jdk.https.negotiate.cbt never

Controls the generation and sending of TLS channel binding tokens (CBT) when Kerberos or the Negotiate authentication scheme using Kerberos are employed over HTTPS with HttpsURLConnection. There are three possible settings:

  • never: This is also the default value if the property is not set. In this case, CBTs are never sent.
  • always: CBTs are sent for all Kerberos authentication attempts over HTTPS.
  • domain:<comma-separated domain list>: Each domain in the list specifies the destination host or hosts for which a CBT is sent. Domains can be:
    • Single hosts like example or example.com
    • Literal IP addresses as specified in RFC 2732
    • Hostnames that contain wildcards like *.example.com; this example matches all hosts under example.com and its subdomains.

The channel binding tokens generated are of the type tls-server-end-point as defined in RFC 5929.

jdk.http.ntlm.transparentAuth No default value

Enables transparent New Technology LAN Manager (NTLM) HTTP authentication on Windows.

Transparent authentication can be used for the NTLM scheme, where the security credentials based on the currently logged in user's name and password can be obtained directly from the operating system, without prompting the user.

If this value is not set, then transparent authentication is never used.

This property has three possible values:

  • disabled: Transparent authentication is never used.
  • allHosts: Transparent. authentication is used for all hosts
  • trustedHosts: Transparent authentication is enabled for hosts that are trusted in Windows Internet settings.

Note that NTLM is not a strongly secure authentication scheme; care should be taken before enabling it.

System Properties That Modify the Behavior of HTTP Digest Authentication Mechanism

The system properties http.auth.digest.validateServer and http.auth.digest.validateProxy modify the behavior of the HTTP digest authentication mechanism. Digest authentication provides a limited ability for the server to authenticate itself to the client (that is, by proving that it knows the user's password). However, not all servers support this capability and by default the check is switched off. To enforce this check for authentication with an origin, set http.auth.digest.validateServer to true; with a proxy server, set http.auth.digest.validateProxy to true.

It is usually not necessary to set the system property http.auth.digest.cnonceRepeat. This determines how many times a cnonce value is reused. This can be useful when the MD5-sess algorithm is being used. Increasing the value reduces the computational overhead on both the client and the server by reducing the amount of material that has to be hashed for each HTTP request.

Specify Mappings from Host Names to IP Addresses

You can customize the mapping from host names to IP addresses by deploying a system-wide resolver. See the InetAddressResolverProvider class in the Java SE API Specification for more information. In cases where this is not practical, such as testing, you can configure InetAddress to use a specific hosts file, rather than the system-wide resolver, to map host names to IP addresses. Specify this hosts file with the system property jdk.net.hosts.file.

Note:

Use a specific hosts file for testing; it's not intended as a general purpose solution because the complete list of host names is not always known in advance.

By default, the system property jdk.net.hosts.file is not set. If it's set, then name service lookups are obtained from the file specified by this system property. If this system property specifies a file that doesn't exist, then it treats it as an empty file, and a name/address lookup throws an UnknownHostException.

The structure of the hosts file is similar to a Linux or macOS /etc/hosts file. Each line of this text file has the following syntax:

IPAddress hostname [host aliases...]
  • IPAddress: IP address
  • hostname: Host name to which the IP address is mapped
    • A host name should have the syntax and structure of a fully qualified domain name (FQDN), composed of alphanumeric characters, hyphens (-), and periods (.). It should begin and end with an alphanumeric character.
    • Note that no syntax checking or host name validation is performed.
  • [host aliases...]: An optional list of host aliases

The fields of an entry are separated by any number of whitespace (spaces and tabs).

A comment, which starts with a number sign (#) and followed by text until the end of the line, is ignored.

The following is an example of a hosts file:

# sample jdk.net.hosts.file entries
127.0.0.1 localhost
127.0.0.1 host.rabbit.hole
127.0.0.1 c1.this.domain
192.0.2.0 testhost.testdomain
192.0.2.255 testhost2.testdomain

Address Cache Properties

The java.net package, when performing name resolution, uses an address cache for both security and performance reasons. Any address resolution attempt, be it forward (name to IP address) or reverse (IP address to name), will have its result cached, whether it was successful or not, so that subsequent identical requests will not have to access the naming service. These properties enable you to tune how the address cache operates.

Note:

The following properties are part of the security policy. They are not set by the -D option or the System.setProperty() method. Instead, they are set as Security Properties.

Table 10-10 Address Cache Properties

Property Default Value Description
networkaddress.cache.ttl -1

Specified in the $JAVA_HOME/conf/security/java.security file to indicate the caching policy for successful name lookups from the name service. The value is an integer corresponding to the number of seconds successful name lookups will be kept in the cache.

A value of -1 (or any other negative value) indicates a “cache forever” policy, while a value of 0 (zero) means no caching.

The default value is -1 (forever) if a security manager is installed and implementation-specific if no security manager is installed.

networkaddress.cache.negative.ttl 10 Specified in the $JAVA_HOME/conf/security/java.security file to indicate the caching policy for unsuccessful name lookups from the name service.

The value is an integer corresponding to the number of seconds an unsuccessful name lookup will be kept in the cache. A value of -1 (or any negative value) means “cache forever,” while a value of 0 (zero) means no caching.

Enhanced Exception Messages

By default, for security reasons, exception messages do not include potentially sensitive security information such as hostnames or UNIX domain socket address paths. Use the jdk.includeInExceptions to relax this restriction for debugging and other purposes.

Table 10-11 Enhanced Exception Messages Property

Property Default Value Description
jdk.includeInExceptions No default value

The value is a omma-separated list of keywords that refer to exception types whose messages may be enhanced with more detailed information.

In particular, if the value includes the string hostInfo, then socket addresses will be included in exception message texts (for example, hostnames and UNIX domain socket address paths).