# Validate and normalize hostnames

> Use U.validhost() and U.tohost() before you connect to a host that comes from a user, and know what U.resolve(), U.connect() and the SMTP server option now reject.

Framework: total5
Product: Total.js 5 (total5@0.0.20)
Language: en
Content-SHA256: dc647694cd422c5e6f2bc091444b681fceae437b85964632c18b7291f4f4683a
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

A hostname can be written in ways that different parts of a system read differently: a name cut at a NUL byte (`attacker.example\0.trusted.example`), an IPv4 address with leading zeros, in hexadecimal or as one number (`0127.0.0.1`, `0x7f.0.0.1`, `127.1`, `2130706433`), or a name with non-ASCII digits. The Node.js security release of 2026-10-21 fixed some of these in `dns` and `tls`; Total.js `0.0.20` also checks them in the framework itself, so it does not depend on the Node.js version that runs it.

Two helpers are public in `U`:

| Call | Returns |
|---|---|
| `U.validhost(host)` | `true` for a plain hostname or a canonical IP literal, `false` for anything else |
| `U.tohost(host)` | The canonical ASCII form (punycode for an international name, dotted decimal for an IPv4 written in another way), or an empty string when the host is not valid |

Look at what `tohost()` says about `0127.0.0.1`: it is **`87.0.0.1`**, because the leading zero makes the number octal. An address that looks like a local one can point somewhere else, which is why the framework refuses the odd forms (`validhost()` is `false`) and why you should store the canonical form that `tohost()` returns.

`U.resolve()` (used by `REQUEST()`) gives an error before the DNS query when the host is not valid. `U.connect()` normalizes `host` and answers `Invalid hostname` when there is nothing valid left, and the `server` of the mail is normalized the same way (an invalid one answers `Invalid SMTP server hostname.`). Call the helpers yourself when you accept a host from a form or from a setting:

```js controllers/hosts.js
exports.install = function() {
	ROUTE('GET /hosts/', hosts);
	ROUTE('GET /connect/', connect);
};

const CASES = ['totaljs.com', '127.0.0.1', '0127.0.0.1', '0x7f.0.0.1', '127.1', '2130706433', 'a b', 'a.example\u0000.trusted.example', 'bücher.example'];

function hosts($) {
	$.json(CASES.map(host => ({ host: host, valid: U.validhost(host), canonical: U.tohost(host) })));
}

function connect($) {
	U.connect({ host: 'a.example\u0000.trusted.example', port: 80 }, function(err) {
		$.json({ error: err ? err.message : null });
	});
}
```
