Go1.10帮他人写一个简单的CGO使用IcmpSendEcho的例子

package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

/*
#include 
#include 
#include 
*/
import "C"

const INADDR_NONE = 0xffffffff

var (
    Ws2_32              = syscall.NewLazyDLL("Ws2_32.dll")
    Iphlpapi            = syscall.NewLazyDLL("Iphlpapi.dll")
    inet_addr_proc      = Ws2_32.NewProc("inet_addr")
    IcmpCreateFile_proc = Iphlpapi.NewProc("IcmpCreateFile")
    IcmpSendEcho_proc   = Iphlpapi.NewProc("IcmpSendEcho")
)

type IP_OPTION_INFORMATION struct {
    Ttl         uint8
    Tos         uint8
    Flags       uint8
    OptionsSize uint8
    OptionsData uintptr
}

type ICMP_ECHO_REPLY struct {
    Address       uint32
    Status        uint32
    RoundTripTime uint32
    DataSize      uint16
    USHORT        uint16
    Data          uintptr
    Options       IP_OPTION_INFORMATION
}

func main() {
    var ip = syscall.StringBytePtr("192.168.0.1")
    ip_addr, _, err := inet_addr_proc.Call(uintptr(unsafe.Pointer(ip)))
    if ip_addr == INADDR_NONE {
        fmt.Println("地址解析错误")
        return
    }
    fd, _, err := IcmpCreateFile_proc.Call()
    if syscall.Handle(fd) == syscall.InvalidHandle {
        fmt.Printf("创建句柄失败:%s\n", err.Error())
        return
    }
    var SendData [32]byte
    copy(SendData[:], []byte("Data Buffer"))

    var reply ICMP_ECHO_REPLY
    var ReplySize = unsafe.Sizeof(reply) + unsafe.Sizeof(SendData)
    var ReplyBuffer = make([]byte, int(ReplySize))

    _, _, err = IcmpSendEcho_proc.Call(fd, ip_addr, uintptr(unsafe.Pointer(&SendData[0])),
        unsafe.Sizeof(SendData), 0, uintptr(unsafe.Pointer(&ReplyBuffer[0])),
        ReplySize, 1000)

    xx := (*ICMP_ECHO_REPLY)(unsafe.Pointer(&ReplyBuffer[0]))
    fmt.Println(xx)
}

你可能感兴趣的:(Golang)