簡體   English   中英

IP 地址到 Int

[英]IP address to Int

所以我在將 IPv4 和 IPv6 轉換為 Int 時遇到問題,但是我發現這個方便的 Go 腳本可以做到這一點,但是我需要它用於 NodeJS。

我已經嘗試過 NPM 中的插件,包括ip2int ,但它似乎已損壞,僅適用於 IPv4。

我想知道是否有人知道如何將 GO 轉換為 nodeJS 的 Javascript。 據我所知,以下代碼適用於 Go。

package main

import (
    "fmt"
    "math/big"
    "net"
)

func Ip2Int(ip net.IP) *big.Int {
    i := big.NewInt(0)
    i.SetBytes(ip)
    return i
}

func main() {
    fmt.Println(Ip2Int(net.ParseIP("20.36.77.12").To4()).String())
    fmt.Println(Ip2Int(net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334").To16()).String())
}

The reason why we need to parse the IP addresses to int is so that when we receive the IP address we can search to see if that IP address is inside one of the ranges of IP addresses that we have collected.

例如 RAPD 返回

 "startAddress": "35.192.0.0",
  "endAddress": "35.207.255.255",

因此,如果我們將這兩個都轉換為 int,我們可以將它們存儲在我們的數據庫中並進行gtelte搜索,看看 IP 地址是否在任何存儲值之間。

請參閱此解決方案

對於 IPv4 使用:

ipv4.split('.').reduce(function(int, value) { return int * 256 + +value })

對於 IPv6,您首先需要解析十六進制值,十六進制值代表 2 個字節:

ipv6.split(':').map(str => Number('0x'+str)).reduce(function(int, value) { return int * 65536 + +value })

我還在引用的要點中添加了 ipv6 解決方案。

const IPv4ToInt = ipv4 => ipv4.split(".").reduce((a, b) => a << 8 | b) >>> 0;

和一個簡單的 IPv6 實現:

const IPv6ToBigInt = ipv6 => BigInt("0x" + ipv6.toLowerCase().split(":").map(v => v.padStart(4, 0)).join(""));

或更廣泛的

 // normalizes several IPv6 formats to the long version // in this format a string sort is equivalent to a numeric sort const normalizeIPv6 = (ipv6) => { // for embedded IPv4 in IPv6. // like "::ffff:127.0.0.1" ipv6 = ipv6.replace(/\d+\.\d+\.\d+\.\d+$/, ipv4 => { const [a, b, c, d] = ipv4.split("."); return (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16) }); // shortened IPs // like "2001:db8::1428:57ab" ipv6 = ipv6.replace("::", ":".repeat(10 - ipv6.split(":").length)); return ipv6.toLowerCase().split(":").map(v => v.padStart(4, 0)).join(":"); } const IPv6ToBigInt = ipv6 => BigInt("0x" + normalizeIPv6(ipv6).replaceAll(":", "")); // tests [ "2001:0db8:85a3:08d3:1319:8a2e:0370:7344", "2001:0db8:85a3:08d3:1319:8a2e:0370:7345", // check precision "2001:db8:0:8d3:0:8a2e:70:7344", "2001:db8:0:0:0:0:1428:57ab", "2001:db8::1428:57ab", "2001:0db8:0:0:8d3:0:0:0", "2001:db8:0:0:8d3::", "2001:db8::8d3:0:0:0", "::ffff:127.0.0.1", "::ffff:7f00:1" ].forEach(ip => console.log({ ip, normalized: normalizeIPv6(ip), bigInt: IPv6ToBigInt(ip).toString() // toString() or SO console doesn't print them. }));
 .as-console-wrapper{top:0;max-height:100%!important}

Javascript(原版)程序:

function ipToInt(value) {
  return Number(value.replace(/[a-z]|:|\./g, ""))
}

const ip1 = "2001:0db8:0:0:8d3:0:0:0"
const ip2 = "35.192.0.0"

console.log("IPv6", ipToInt(ip1))
console.log("IPv4", ipToInt(ip2))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM