Skip to content

Instantly share code, notes, and snippets.

@flower1024
Last active August 3, 2024 08:03
Show Gist options
  • Save flower1024/f3ef6311f987b73e2a98cf773fd21796 to your computer and use it in GitHub Desktop.
Save flower1024/f3ef6311f987b73e2a98cf773fd21796 to your computer and use it in GitHub Desktop.
Get IPv4 and IPv6 WAN IP from FritzBox
import { parse as xmlParser } from 'fsp-xml-parser';
export default class FritzBoxIP {
private _fritzBox: string;
constructor(fritzBox: string) {
this._fritzBox = fritzBox;
}
async IPv4(): Promise<string> {
const xml = await fetch(`${this._fritzBox}/igdupnp/control/WANIPConn1`, {
headers: {
"Content-Type": "text/xml; charset=utf-8",
"SoapAction": "urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress"
},
method: "POST",
body: "<?xml version='1.0' encoding='utf-8'?> <s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'> <s:Body> <u:GetExternalIPAddress xmlns:u='urn:schemas-upnp-org:service:WANIPConnection:1' /> </s:Body> </s:Envelope>"
});
const IP4 = xmlParser(await xml.text());
return IP4.root!.children![0].children![0].children![0].content!;
}
async IPv6(): Promise<string> {
const xml = await fetch(`${this._fritzBox}/igdupnp/control/WANIPConn1`, {
headers: {
"Content-Type": "text/xml; charset=utf-8",
"SoapAction": "urn:schemas-upnp-org:service:WANIPConnection:1#X_AVM_DE_GetExternalIPv6Address"
},
method: "POST",
body: "<?xml version='1.0' encoding='utf-8'?> <s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'> <s:Body> <u:GetExternalIPAddress xmlns:u='urn:schemas-upnp-org:service:WANIPConnection:1' /> </s:Body> </s:Envelope>"
});
const IP6 = xmlParser(await xml.text());
return IP6.root!.children![0].children![0].children![0].content!;
}
}
import FritzBoxIP from "./FritzBoxIP";
const fritzBoxIP = new FritzBoxIP({ "FritzBox": "http://fritz.box:49000" });
let IPv4: string;
let IPv6: string;
try {
IPv4 = await fritzBoxIP.IPv4();
IPv6 = await fritzBoxIP.IPv6();
} catch(e) {
console.log("ERROR", "Can't get WAN IP", e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment