golang搭建一个dhcp分配局域网ip地址服务代码

代码语言:golang

所属分类:其他

代码描述:golang搭建一个dhcp分配局域网ip地址服务代码

代码标签: golang dhcp 分配 局域网 ip 地址 服务 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

package main

import (
    "log"
    "net"
    "time"

    "github.com/krolaw/dhcp4"
    "github.com/krolaw/dhcp4/conn"
)

type DHCPHandler struct {
    ip          net.IP
    start       net.IP
    leaseRange  int
    leaseDuration time.Duration
    leases      map[string]lease
    options     dhcp4.Options
}

type lease struct {
    nic    string
    expiry time.Time
}

func (h *DHCPHandler) ServeDHCP(pkt dhcp4.Packet, msgType dhcp4.MessageType, options dhcp4.Options) dhcp4.Packet {
    switch msgType {
    case dhcp4.Discover:
        freeIP := h.getFreeIP()
        if freeIP == nil {
            return nil
        }
        h.leases[freeIP.String()] = lease{nic: pkt.CHAddr().String(), expiry: time.Now().Add(h.leaseDuration)}
        return dhcp4.ReplyPacket(pkt, dhcp4.Offer, h.ip, freeIP, h.leaseDuration,
            h.options.SelectOrderOrAll(options[dhcp4.OptionParameterRequestList]))
    case dhcp4.Request:
        reqIP := net.IP(options[dhcp4.OptionRequestedIPAddress])
        if reqIP == nil {
            reqIP = net.IP(pkt.CIAddr())
        }
        if lease, ok := h.leases[reqIP.String()]; ok && lease.nic == pkt.CHAddr().String() {
            h.leases[reqIP.String()] = lease{nic: pkt.CHAddr().String(), expiry: time.Now().Add(h.leaseDuration)}
       .........完整代码请登录后点击上方下载按钮下载查看

网友评论0