MISC: Updated createRandomIP to use the full 32 bit space (#2113)

This commit is contained in:
whiskeyfur
2025-05-14 01:17:52 -07:00
committed by GitHub
parent 48f6de9cf5
commit 5e2d038e05
2 changed files with 41 additions and 30 deletions
+13 -2
View File
@@ -1,10 +1,21 @@
import type { IPAddress } from "../Types/strings";
import { getRandomByte } from "./helpers/getRandomByte";
/**
* Generate a random IP address
* Does not check to see if the IP already exists in the game
*/
export const createRandomIp = (): IPAddress => {
return `${getRandomByte(99)}.${getRandomByte(9)}.${getRandomByte(9)}.${getRandomByte(9)}` as IPAddress;
// Credit goes to yichizhng on BitBurner discord
// Generates a number like 0.c8f0a07f1d47e8
const ip = Math.random().toString(16);
// uses regex to match every 2 characters. [0.][c8][f0][a0][7f][1d][47][e8]
// we only want #1 through #4
const matchResult = ip.match(/../g);
if (!matchResult) {
// This case should never happen.
throw new Error(`Unexpected regex matching bug in createRandomIp. ip: ${ip}`);
}
const sliced = matchResult.slice(1, 5);
//convert each to a decimal number and join them together to make a human readable IP address.
return sliced.map((x) => parseInt(x, 16)).join(".") as IPAddress;
};