【发布时间】:2019-12-23 01:02:10
【问题描述】:
我正在尝试解析大量 IP(约 20mb 或 400 万个 IP),将它们作为字节存储在文件中,然后再读取它们。
我遇到的问题是我希望它们按排序顺序存储,但我看到随机字节切片在读回它们时看起来像是损坏的 IP。
// 让这个叫做 generator.go
var buf []byte
// So this is where we build up `buf`, which we later write to a file.
func writeOut(record RecordStruct) {
// This line is never hit. All slices have a length of 4, as expected
if len(record.IPEnd.Bytes()) != 4 {
fmt.Println(len(record.IPEnd.Bytes()), record.IPEnd.Bytes())
}
// Let's append the IP to the byte slice with a seperater of 10 null bytes which we will later call bytes.Split on.
buf = append(buf, append(record.IPEnd.Bytes(), bytes.Repeat([]byte{0}, 10)...)...)
}
func main () {
// Called many times. For brevity I won't include all of that logic.
// There are no Goroutines in the code and running with -race says all is fine.
writeOut(...)
err := ioutil.WriteFile("bin/test", buf, 0644)
}
reader.go
func main() {
bytez, err := ioutil.ReadFile("bin/test")
if err != nil {
fmt.Println("Asset was not found.")
}
haystack := bytes.Split(bytez, bytes.Repeat([]byte{0}, 10))
for _, needle := range haystack {
// Get's hit maybe 10% of the time. The logs are below.
if len(needle) != 4 {
fmt.Println(fmt.Println(needle))
}
}
}
[188 114 235]
14 <nil>
[120 188 114 235 121]
22 <nil>
[188 148 98]
13 <nil>
[120 188 148 98 121]
21 <nil>
如您所见,IP 位太少或太多。
如果我更改日志以更好地说明问题,看起来最后一个八位字节溢出了?
Fine: [46 36 202 235]
Fine: [46 36 202 239]
Fine: [46 36 202 255]
Weird: [46 36 203]
Weird: [0 46 36 203 1]
Fine: [46 36 203 3]
Fine: [46 36 203 5]
Fine: [46 36 203 7]
Fine: [46 36 203 9]
【问题讨论】:
-
每次输出(损坏的条目)都一样吗?
-
等等,你的任何条目都是以 0 开头还是结尾?
-
IP 地址以零字节结尾时,代码没有正确拆分字节。
-
@CeriseLimón 我认为你在那里有所作为。所有这些日志都遵循这种模式。有好的解决办法吗?
-
Convert all address to 16 byte representation 并存储为没有分隔符的 16 字节记录。