idn_to_ascii
idn_to_ascii(string $domain, int $flags = IDNA_DEFAULT, int $variant = INTL_IDNA_VARIANT_UTS46, array &$idna_info = null): string|false
Converts an internationalized domain name to IDNA ASCII (punycode): non-ASCII labels become xn-- labels, pure-ASCII ones are only lowercased; UTS #46 is the default variant. The Chinese domain 例子.cn becomes xn--fsqu00a.cn — the UTS #46 rules are frozen, so output is identical across ICU versions.
C C23
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* C has no IDNA in its standard library: RFC 3492 punycode, hand-rolled
(bootstrapping-only demo; production code links libidn2 or ICU) */
enum { BASE = 36, TMIN = 1, TMAX = 26, SKEW = 38, DAMP = 700 };
enum { INIT_BIAS = 72, INIT_N = 128 };
static int adapt(int delta, int num_points, bool first_time) {
delta /= first_time ? DAMP : 2;
delta += delta / num_points;
int k = 0;
while (delta > (BASE - TMIN) * TMAX / 2) {
delta /= BASE - TMIN;
k += BASE;
}
return k + (BASE - TMIN + 1) * delta / (delta + SKEW);
}
static char encode_digit(int d) {
return d < 26 ? (char)('a' + d) : (char)('0' + d - 26);
}
/* decode one UTF-8 label into UTF-32 code points */
static size_t utf8_decode(const char *s, size_t len, unsigned *cps) {
size_t n = 0;
for (size_t i = 0; i < len; ) {
unsigned char c = (unsigned char)s[i];
if (c < 0x80) {
cps[n++] = c;
i += 1;
} else if ((c >> 5) == 0x6) {
cps[n++] = ((c & 0x1Fu) << 6) | ((unsigned char)s[i + 1] & 0x3Fu);
i += 2;
} else if ((c >> 4) == 0xE) {
cps[n++] = ((c & 0x0Fu) << 12) | (((unsigned char)s[i + 1] & 0x3Fu) << 6) |
((unsigned char)s[i + 2] & 0x3Fu);
i += 3;
} else {
cps[n++] = ((c & 0x07u) << 18) | (((unsigned char)s[i + 1] & 0x3Fu) << 12) |
(((unsigned char)s[i + 2] & 0x3Fu) << 6) | ((unsigned char)s[i + 3] & 0x3Fu);
i += 4;
}
}
return n;
}
/* encode one label (UTF-32) into punycode; returns a malloc'd string */
static char *punycode_encode(const unsigned *cps, size_t len) {
int n = INIT_N, delta = 0, bias = INIT_BIAS;
size_t h = 0, b = 0, olen = 0;
size_t cap = 4 * len + 16;
char *out = malloc(cap);
for (size_t i = 0; i < len; i++) {
if (cps[i] < 128) {
out[olen++] = (char)cps[i];
h++;
}
}
b = h;
if (b > 0) out[olen++] = '-';
while (h < len) {
unsigned m = UINT_MAX;
for (size_t i = 0; i < len; i++)
if (cps[i] >= (unsigned)n && cps[i] < m) m = cps[i];
delta += ((int)m - n) * (int)(h + 1);
n = (int)m;
for (size_t i = 0; i < len; i++) {
if (cps[i] < (unsigned)n) delta++;
if (cps[i] == (unsigned)n) {
int q = delta;
for (int k = BASE; ; k += BASE) {
int t = k - bias;
if (t < TMIN) t = TMIN;
if (t > TMAX) t = TMAX;
if (q < t) break;
out[olen++] = encode_digit(t + (q - t) % (BASE - t));
q = (q - t) / (BASE - t);
}
out[olen++] = encode_digit(q);
bias = adapt(delta, (int)(h + 1), h == b);
delta = 0;
h++;
}
}
delta++;
n++;
}
out[olen] = '\0';
return out;
}
static bool is_ascii(const char *s, size_t len) {
for (size_t i = 0; i < len; i++)
if ((unsigned char)s[i] > 0x7f) return false;
return true;
}
/* mirrors the UTS #46 shape: punycode non-ASCII labels, lowercase the rest */
static void to_ascii(const char *domain) {
const char *p = domain;
bool first = true;
while (1) {
const char *dot = strchr(p, '.');
size_t len = dot ? (size_t)(dot - p) : strlen(p);
if (!first) putchar('.');
first = false;
if (is_ascii(p, len)) {
for (size_t i = 0; i < len; i++) putchar(tolower((unsigned char)p[i]));
} else {
unsigned cps[64];
size_t n = utf8_decode(p, len, cps);
char *enc = punycode_encode(cps, n);
printf("xn--%s", enc);
free(enc);
}
if (!dot) break;
p = dot + 1;
}
putchar('\n');
}
int main(void) {
to_ascii("例子.cn");
to_ascii("täst.de");
to_ascii("Example.COM");
return 0;
}
xn--fsqu00a.cn xn--tst-qla.de example.com
C++ C++26
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// C++ has no IDNA in its standard library: RFC 3492 punycode, hand-rolled
// (bootstrapping-only demo; production code links ICU or uses libidn2)
namespace {
constexpr int kBase = 36, kTmin = 1, kTmax = 26, kSkew = 38, kDamp = 700;
constexpr int kInitBias = 72, kInitN = 128;
int adapt(int delta, int numPoints, bool firstTime) {
delta /= firstTime ? kDamp : 2;
delta += delta / numPoints;
int k = 0;
while (delta > (kBase - kTmin) * kTmax / 2) {
delta /= kBase - kTmin;
k += kBase;
}
return k + (kBase - kTmin + 1) * delta / (delta + kSkew);
}
char encodeDigit(int d) {
return d < 26 ? static_cast<char>('a' + d) : static_cast<char>('0' + d - 26);
}
// label as UTF-32 code points
std::string punycodeEncode(const std::vector<unsigned> &cps) {
int n = kInitN, delta = 0, bias = kInitBias;
std::string out;
std::size_t h = 0, b = 0;
for (unsigned c : cps) {
if (c < 128) {
out += static_cast<char>(c);
h++;
}
}
b = h;
if (b > 0) out += '-';
while (h < cps.size()) {
unsigned m = 0xFFFFFFFFu;
for (unsigned c : cps)
if (c >= static_cast<unsigned>(n) && c < m) m = c;
delta += (static_cast<int>(m) - n) * static_cast<int>(h + 1);
n = static_cast<int>(m);
for (unsigned c : cps) {
if (c < static_cast<unsigned>(n)) delta++;
if (c == static_cast<unsigned>(n)) {
int q = delta;
for (int k = kBase; ; k += kBase) {
int t = std::max(kTmin, std::min(k - bias, kTmax));
if (q < t) break;
out += encodeDigit(t + (q - t) % (kBase - t));
q = (q - t) / (kBase - t);
}
out += encodeDigit(q);
bias = adapt(delta, static_cast<int>(h + 1), h == b);
delta = 0;
h++;
}
}
delta++;
n++;
}
return out;
}
// decode one UTF-8 label into UTF-32 code points
std::vector<unsigned> utf8Decode(const std::string &s) {
std::vector<unsigned> cps;
for (std::size_t i = 0; i < s.size(); ) {
unsigned char c = static_cast<unsigned char>(s[i]);
if (c < 0x80) {
cps.push_back(c);
i += 1;
} else if ((c >> 5) == 0x6) {
cps.push_back(((c & 0x1Fu) << 6) | (static_cast<unsigned char>(s[i + 1]) & 0x3Fu));
i += 2;
} else if ((c >> 4) == 0xE) {
cps.push_back(((c & 0x0Fu) << 12) |
((static_cast<unsigned char>(s[i + 1]) & 0x3Fu) << 6) |
(static_cast<unsigned char>(s[i + 2]) & 0x3Fu));
i += 3;
} else {
cps.push_back(((c & 0x07u) << 18) |
((static_cast<unsigned char>(s[i + 1]) & 0x3Fu) << 12) |
((static_cast<unsigned char>(s[i + 2]) & 0x3Fu) << 6) |
(static_cast<unsigned char>(s[i + 3]) & 0x3Fu));
i += 4;
}
}
return cps;
}
bool isASCII(const std::string &s) {
return std::all_of(s.begin(), s.end(), [](unsigned char c) { return c <= 0x7f; });
}
// mirrors the UTS #46 shape: punycode non-ASCII labels, lowercase the rest
std::string toASCII(const std::string &domain) {
std::istringstream in(domain);
std::string label, out;
while (std::getline(in, label, '.')) {
if (!out.empty()) out += '.';
if (isASCII(label)) {
std::transform(label.begin(), label.end(), label.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
out += label;
} else {
out += "xn--" + punycodeEncode(utf8Decode(label));
}
}
return out;
}
} // namespace
int main() {
std::cout << toASCII("例子.cn") << "\n";
std::cout << toASCII("täst.de") << "\n";
std::cout << toASCII("Example.COM") << "\n";
return 0;
}
xn--fsqu00a.cn xn--tst-qla.de example.com
C# v11.0.100
// IdnMapping is the BCL-native IDNA engine
using System.Globalization;
var idn = new IdnMapping();
Console.WriteLine(idn.GetAscii("例子.cn"));
Console.WriteLine(idn.GetAscii("täst.de"));
Console.WriteLine(idn.GetAscii("Example.COM").ToLowerInvariant()); // GetAscii keeps ASCII case
xn--fsqu00a.cn xn--tst-qla.de example.com
Go v1.27.4
package main
import (
"fmt"
"strings"
)
// Go stdlib has no IDNA: RFC 3492 punycode, hand-rolled (bootstrapping-only demo)
const (
base = 36
tmin = 1
tmax = 26
skew = 38
damp = 700
initBias = 72
initN = 128
)
const maxInt = int(^uint(0) >> 1)
func adapt(delta, numPoints int, firstTime bool) int {
if firstTime {
delta /= damp
} else {
delta /= 2
}
delta += delta / numPoints
k := 0
for delta > (base-tmin)*tmax/2 {
delta /= base - tmin
k += base
}
return k + (base-tmin+1)*delta/(delta+skew)
}
func encodeDigit(d int) byte {
if d < 26 {
return byte('a' + d)
}
return byte('0' + d - 26)
}
func clamp(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
func punycodeEncode(label string) string {
runes := []rune(label)
n, delta, bias := initN, 0, initBias
var out strings.Builder
h, b := 0, 0
for _, r := range runes {
if r < 128 {
out.WriteByte(byte(r))
h++
}
}
b = h
if b > 0 {
out.WriteByte('-')
}
for h < len(runes) {
m := maxInt
for _, r := range runes {
if int(r) >= n && int(r) < m {
m = int(r)
}
}
delta += (m - n) * (h + 1)
n = m
for _, r := range runes {
if int(r) < n {
delta++
}
if int(r) == n {
q := delta
for k := base; ; k += base {
t := clamp(k-bias, tmin, tmax)
if q < t {
break
}
out.WriteByte(encodeDigit(t + (q-t)%(base-t)))
q = (q - t) / (base - t)
}
out.WriteByte(encodeDigit(q))
bias = adapt(delta, h+1, h == b)
delta = 0
h++
}
}
delta++
n++
}
return out.String()
}
func isASCII(s string) bool {
for _, r := range s {
if r > 0x7f {
return false
}
}
return true
}
// toASCII mirrors the UTS #46 shape: punycode non-ASCII labels, lowercase the rest
func toASCII(domain string) string {
labels := strings.Split(domain, ".")
for i, l := range labels {
if isASCII(l) {
labels[i] = strings.ToLower(l)
} else {
labels[i] = "xn--" + punycodeEncode(l)
}
}
return strings.Join(labels, ".")
}
func main() {
fmt.Println(toASCII("例子.cn"))
fmt.Println(toASCII("täst.de"))
fmt.Println(toASCII("Example.COM"))
}
xn--fsqu00a.cn xn--tst-qla.de example.com
Java v27.0.1
import java.net.IDN;
public class Main {
public static void main(String[] args) {
// java.net.IDN is the JDK-native IDNA engine
System.out.println(IDN.toASCII("例子.cn"));
System.out.println(IDN.toASCII("täst.de"));
System.out.println(IDN.toASCII("Example.COM").toLowerCase());
}
}
xn--fsqu00a.cn xn--tst-qla.de example.com
JavaScript v26.13.1
// JS has no IDNA in stdlib: RFC 3492 punycode, hand-rolled (bootstrapping-only demo)
const BASE = 36, TMIN = 1, TMAX = 26, SKEW = 38, DAMP = 700;
const INIT_BIAS = 72, INIT_N = 128;
function adapt(delta, numPoints, firstTime) {
delta = Math.floor(delta / (firstTime ? DAMP : 2));
delta += Math.floor(delta / numPoints);
let k = 0;
while (delta > Math.floor(((BASE - TMIN) * TMAX) / 2)) {
delta = Math.floor(delta / (BASE - TMIN));
k += BASE;
}
return k + Math.floor(((BASE - TMIN + 1) * delta) / (delta + SKEW));
}
const digit = (d) => (d < 26 ? String.fromCharCode(97 + d) : String.fromCharCode(48 + d - 26));
function punycodeEncode(input) {
const cps = [...input].map((c) => c.codePointAt(0));
let n = INIT_N, delta = 0, bias = INIT_BIAS;
let out = '';
let h = 0;
for (const c of cps) if (c < 128) { out += String.fromCharCode(c); h++; }
const b = h;
if (b > 0) out += '-';
while (h < cps.length) {
let m = Infinity;
for (const c of cps) if (c >= n && c < m) m = c;
delta += (m - n) * (h + 1);
n = m;
for (const c of cps) {
if (c < n) delta++;
if (c === n) {
let q = delta;
for (let k = BASE; ; k += BASE) {
const t = Math.max(TMIN, Math.min(k - bias, TMAX));
if (q < t) break;
out += digit(t + ((q - t) % (BASE - t)));
q = Math.floor((q - t) / (BASE - t));
}
out += digit(q);
bias = adapt(delta, h + 1, h === b);
delta = 0;
h++;
}
}
delta++;
n++;
}
return out;
}
const toASCII = (domain) =>
domain.split('.').map((l) =>
/^[\x00-\x7f]*$/.test(l) ? l.toLowerCase() : 'xn--' + punycodeEncode(l)).join('.');
console.log(toASCII('例子.cn'));
console.log(toASCII('täst.de'));
console.log(toASCII('Example.COM'));
xn--fsqu00a.cn xn--tst-qla.de example.com
PHP v8.6.0
// UTS #46 (IDNA): every non-ASCII label becomes an xn-- punycode label
echo idn_to_ascii('例子.cn'), "\n";
echo idn_to_ascii('täst.de'), "\n";
echo idn_to_ascii('Example.COM'), "\n"; // all-ASCII labels: lowercased only
xn--fsqu00a.cn xn--tst-qla.de example.com
Python v3.15.2
# stdlib's idna codec does the same punycode transform on non-ASCII labels
print('例子.cn'.encode('idna').decode())
print('täst.de'.encode('idna').decode())
print('Example.COM'.encode('idna').decode().lower())
xn--fsqu00a.cn xn--tst-qla.de example.com
Rust v1.99.1
// Rust has no IDNA in std: RFC 3492 punycode, hand-rolled (demo; use the `idna` crate in production)
const BASE: i32 = 36;
const TMIN: i32 = 1;
const TMAX: i32 = 26;
const SKEW: i32 = 38;
const DAMP: i32 = 700;
const INIT_BIAS: i32 = 72;
const INIT_N: i32 = 128;
fn adapt(mut delta: i32, num_points: i32, first_time: bool) -> i32 {
delta /= if first_time { DAMP } else { 2 };
delta += delta / num_points;
let mut k = 0;
while delta > (BASE - TMIN) * TMAX / 2 {
delta /= BASE - TMIN;
k += BASE;
}
k + (BASE - TMIN + 1) * delta / (delta + SKEW)
}
fn encode_digit(d: i32) -> char {
if d < 26 {
(b'a' + d as u8) as char
} else {
(b'0' + (d - 26) as u8) as char
}
}
fn punycode_encode(label: &str) -> String {
let cps: Vec<u32> = label.chars().map(|c| c as u32).collect();
let (mut n, mut delta, mut bias) = (INIT_N, 0, INIT_BIAS);
let mut out = String::new();
let mut h = 0usize;
for &c in &cps {
if c < 128 {
out.push(c as u8 as char);
h += 1;
}
}
let b = h;
if b > 0 {
out.push('-');
}
while h < cps.len() {
let m = *cps.iter().filter(|&&c| c as i32 >= n).min().unwrap() as i32;
delta += (m - n) * (h as i32 + 1);
n = m;
for &c in &cps {
if (c as i32) < n {
delta += 1;
}
if c as i32 == n {
let mut q = delta;
let mut k = BASE;
loop {
let t = (k - bias).clamp(TMIN, TMAX);
if q < t {
break;
}
out.push(encode_digit(t + (q - t) % (BASE - t)));
q = (q - t) / (BASE - t);
k += BASE;
}
out.push(encode_digit(q));
bias = adapt(delta, h as i32 + 1, h == b);
delta = 0;
h += 1;
}
}
delta += 1;
n += 1;
}
out
}
fn to_ascii(domain: &str) -> String {
domain
.split('.')
.map(|l| {
if l.is_ascii() {
l.to_lowercase()
} else {
format!("xn--{}", punycode_encode(l))
}
})
.collect::<Vec<_>>()
.join(".")
}
fn main() {
println!("{}", to_ascii("例子.cn"));
println!("{}", to_ascii("täst.de"));
println!("{}", to_ascii("Example.COM"));
}
xn--fsqu00a.cn xn--tst-qla.de example.com
TypeScript v26.13.1
// TS has no IDNA in stdlib either: RFC 3492 punycode, hand-rolled (demo only)
const BASE: number = 36, TMIN: number = 1, TMAX: number = 26, SKEW: number = 38, DAMP: number = 700;
const INIT_BIAS: number = 72, INIT_N: number = 128;
function adapt(delta: number, numPoints: number, firstTime: boolean): number {
delta = Math.floor(delta / (firstTime ? DAMP : 2));
delta += Math.floor(delta / numPoints);
let k: number = 0;
while (delta > Math.floor(((BASE - TMIN) * TMAX) / 2)) {
delta = Math.floor(delta / (BASE - TMIN));
k += BASE;
}
return k + Math.floor(((BASE - TMIN + 1) * delta) / (delta + SKEW));
}
const digit = (d: number): string => (d < 26 ? String.fromCharCode(97 + d) : String.fromCharCode(48 + d - 26));
function punycodeEncode(input: string): string {
const cps: number[] = [...input].map((c) => c.codePointAt(0)!);
let n: number = INIT_N, delta: number = 0, bias: number = INIT_BIAS;
let out: string = '';
let h: number = 0;
for (const c of cps) if (c < 128) { out += String.fromCharCode(c); h++; }
const b: number = h;
if (b > 0) out += '-';
while (h < cps.length) {
let m: number = Infinity;
for (const c of cps) if (c >= n && c < m) m = c;
delta += (m - n) * (h + 1);
n = m;
for (const c of cps) {
if (c < n) delta++;
if (c === n) {
let q: number = delta;
for (let k: number = BASE; ; k += BASE) {
const t: number = Math.max(TMIN, Math.min(k - bias, TMAX));
if (q < t) break;
out += digit(t + ((q - t) % (BASE - t)));
q = Math.floor((q - t) / (BASE - t));
}
out += digit(q);
bias = adapt(delta, h + 1, h === b);
delta = 0;
h++;
}
}
delta++;
n++;
}
return out;
}
const toASCII = (domain: string): string =>
domain.split('.').map((l) =>
/^[\x00-\x7f]*$/.test(l) ? l.toLowerCase() : 'xn--' + punycodeEncode(l)).join('.');
console.log(toASCII('例子.cn'));
console.log(toASCII('täst.de'));
console.log(toASCII('Example.COM'));
xn--fsqu00a.cn xn--tst-qla.de example.com
Language differences
PHP: idn_to_ascii($domain, $flags, $variant, &$info) defaults to INTL_IDNA_VARIANT_UTS46 (since 7.4; the 2003 variant is deprecated since 7.2 and passing a non-UTS46 variant throws ValueError since 8.4) + IDNA_DEFAULT; $info returns result/isTransitionalDifferent/errors (an IDNA_ERROR_* bitset); an empty string throws ValueError since 8.4; convert domain labels only — never pass a scheme or path (a manual user note shows the full-URL version that parse_url's first). The inverse is idn_to_utf8(). Modern registries require UTS46 + NONTRANSITIONAL processing (IDNA2008-compatible: teßt must not become ss).
Determinism argument: punycode is a frozen RFC 3492 algorithm — the encoding of 例子, "fsqu00a", is uniquely determined by its code points and independent of ICU version and OS; this machine's ICU 79.1 and CI's output are byte-identical (verified). The real divergence point is the mapping phase (case folding, transitional handling like ß→ss), which the sample deliberately avoids: pure-Chinese labels plus ASCII labels that only lowercase.
C/C++: no standard solution; the example hand-rolls RFC 3492 (including UTF-8→UTF-32 decoding) and matches ICU output; production links libidn2/libidn or ICU.
C#: IdnMapping.GetAscii is native; note it preserves ASCII case (the example adds ToLowerInvariant); GetUnicode is the inverse.
Java: java.net.IDN.toASCII is native (JDK-bundled implementation, IDNA2003 school); the sample agrees with UTS46 only because there is no mapping divergence.
JS/TS: no built-in (Node's punycode core module is deprecated); the example hand-rolls RFC 3492 and matches the native APIs; in production use url.domainToASCII (Node >= 10's url module!) or the punycode.js userland package.
Python: '域名'.encode('idna') is native (built-in codec, IDNA2003 school); the sample agrees only because there is no mapping divergence; for exact UTS46 semantics use the third-party idna package.
Go: golang.org/x/net/idna (ToASCII/ToUnicode, UTS46).
Rust: the idna crate (fetched via cargo); nothing in std.
Security note: compare/whitelist domains in ASCII form (per the UTS #46 security section) and normalize with idn_to_ascii first to block homograph bypasses.