golang-ip寻址面试题

给你一个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
}

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值