栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang-ip寻址面试题

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号