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

package main

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

/*
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
*/
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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值