mirror of
https://github.com/bitburner-official/bitburner-src.git
synced 2026-04-29 04:17:05 +02:00
MISC: Updated createRandomIP to use the full 32 bit space (#2113)
This commit is contained in:
+13
-2
@@ -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;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user