duan0708676887 2015-07-02 17:48
浏览 36
已采纳

如何获得下一个IP地址?

I'm considering to call net.IP.String(), strings.Split(ip, "."), some code to calculate all the corner cases and finally net.ParseIP(s). Is there a better way to this?. Below is the code of my current implementation (no special case handled).

package main

import (
    "fmt"
    "net"
    "strconv"
    "strings"
)

func main() {
    ip := net.ParseIP("127.1.0.0")
    next, err := NextIP(ip)
    if err != nil {
        panic(err)
    }
    fmt.Println(ip, next)
}

func NextIP(ip net.IP) (net.IP, error) {
    s := ip.String()
    sa := strings.Split(s, ".")
    i, err := strconv.Atoi(sa[2])
    if err != nil {
        return nil, err
    }
    i++
    sa[3] = strconv.Itoa(i)
    s = strings.Join(sa, ".")
    return net.ParseIP(s), nil
}
  • 写回答

4条回答 默认 最新

  • dty98339 2015-07-02 18:14
    关注

    Just increment the last octet in the IP address

    ip := net.ParseIP("127.1.0.0")
    // make sure it's only 4 bytes
    ip = ip.To4()
    // check ip != nil
    ip[3]++  // check for rollover
    fmt.Println(ip)
    //127.1.0.1
    

    That however is technically incorrect, since the first address in the 127.1.0.1/8 subnet is 127.0.0.1. To get the true "first" address, you will also need an IPMask. Since you didn't specify one, you could use DefaultMask for IPv4 addresses (for IPv6 you can't assume a mask, and you must provide it).

    http://play.golang.org/p/P_QWwRIBIm

    ip := net.IP{192, 168, 1, 10}
    ip = ip.To4()
    if ip == nil {
        log.Fatal("non ipv4 address")
    }
    
    ip = ip.Mask(ip.DefaultMask())
    ip[3]++
    
    fmt.Println(ip)
    //192.168.1.1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何实现从tello无人机上获取视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决