Force Curl to Resolve Hostname to a Specific IP

This article explains how to force the curl command-line tool to resolve a specific domain name to a custom IP address without modifying your system’s global hosts file. You will learn about the primary method using the --resolve option, alternative approaches like --connect-to, and how these techniques can be used for testing, development, and debugging web servers.

The Best Method: Using the --resolve Option

The most efficient and clean way to force a custom IP resolution in curl is by using the --resolve parameter. This option acts as a temporary, command-specific host file entry. It redirects traffic for a specific host and port to a destination IP of your choice.

The syntax for the --resolve option is:

curl --resolve <hostname>:<port>:<ip-address> <URL>

Example:

If you want to test how your local server at 127.0.0.1 responds to requests for example.com over HTTPS (port 443), run the following command:

curl --resolve example.com:443:127.0.0.1 https://example.com

In this example: * example.com:443 is the hostname and port you want to intercept. * 127.0.0.1 is the custom IP address you want to force curl to use. * https://example.com is the actual URL you are requesting.

Using this method ensures that SNI (Server Name Indication) and TLS certificates are handled correctly, as the HTTP Host header remains unchanged.


The Alternative Method: Using --connect-to

Another option available in modern versions of curl is --connect-to. Instead of mapping a hostname to an IP, this option redirects a request from a specific target authorization to a different target.

The syntax for --connect-to is:

curl --connect-to <original-host>:<original-port>:<connect-to-host>:<connect-to-port> <URL>

Example:

To redirect requests meant for example.com on port 443 to 127.0.0.1 on port 443, use:

curl --connect-to example.com:443:127.0.0.1:443 https://example.com

This is particularly useful when you want to redirect traffic to a different port on the target machine as well.


The Legacy Method: Passing the Host Header

Before the --resolve option was introduced, developers manually changed the target IP in the URL and passed the original domain inside the HTTP Host header.

curl -H "Host: example.com" http://127.0.0.1/

Warning: While this method works for standard HTTP, it fails for HTTPS connections because curl will attempt to perform a TLS handshake with the IP address 127.0.0.1 rather than the domain name, resulting in SSL certificate validation errors. For secure connections, always use the --resolve method.