当前位置: 首页 > 工具软件 > go-ip > 使用案例 >

golang-ip寻址面试题

宋智明
2023-12-01
给你一个500行的文件,已知文件为有序ip段+地址,内如格式如下:
127.1.0.0 127.1.0.255 地址1
127.1.1.0 127.1.1.255 地址2
127.1.2.0 127.1.2.255 地址3
127.1.3.0 127.1.3.255 地址4
127.1.4.0 127.1.4.255 地址5

写一个算法,传入ip地址,获取到地址详情。
以下代码为本人撸出来的,大家给意见吧
package main

import (
    "os"
    "bufio"
    "io"
    "fmt"
    "strings"
    "strconv"
)

type ip struct {
    start int
    end int
    ipStart string
    ipEnd string
    address string
}

var data []ip

func main()  {
    data = make([]ip, 0)
    data = fGet("./ip.txt")
    fmt.Println(searchs("127.1.3.8"))
}

func fGet(file string) []ip {
    ipStruct := ip{
        start:   0,
        end:     0,
        ipStart: "",
        ipEnd: "",
        address: "",
    }
    ipSlice := []ip{}

    fileSource, err := os.Open(file)
    if err != nil {
        panic("文件不可用")
    }
    fread := bufio.NewReader(fileSource)
    for {
        line, _, err := fread.ReadLine()
        if err == io.EOF {
            break
        }
        lines := strings.Split(string(line), " ")
        ipStruct.start = stringIpToInt(lines[0])
        ipStruct.end = stringIpToInt(lines[1])
        ipStruct.ipStart = lines[0]
        ipStruct.ipEnd = lines[1]
        ipStruct.address = lines[2]
        ipSlice = append(ipSlice, ipStruct)
    }

    return ipSlice
}

func stringIpToInt(ipstring string) int {
    ipSegs := strings.Split(ipstring, ".")
    var ipInt int = 0
    var pos uint = 24
    for _, ipSeg := range ipSegs {
        tempInt, _ := strconv.Atoi(ipSeg)
        tempInt = tempInt << pos
        ipInt = ipInt | tempInt
        pos -= 8
    }
    return ipInt
}

func searchs(ip string) string {
    ipInt := stringIpToInt(ip)
    start := 0
    end := len(data)-1
    index := 0
    address := ""
    for{
        if index == (start + end)/2 {
            break
        }
        index = (start + end)/2
        if data[index].start < ipInt && data[index].end > ipInt {
            address = data[index].address
            break
        } else if data[index].start > ipInt {
            end = index
            continue
        } else if data[index].end < ipInt {
            start = index
            continue
        }
    }
    return address
}
 类似资料: