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

前端之家收集整理的这篇文章主要介绍了Go1.10帮他人写一个简单的CGO使用IcmpSendEcho的例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package@H_404_2@ main

import@H_404_2@ (
    "fmt"@H_404_2@
    "syscall"@H_404_2@
    "unsafe"@H_404_2@
)

/* #include <winsock2.h> #include <iphlpapi.h> #include <icmpapi.h> */@H_404_2@
import@H_404_2@ "C"@H_404_2@

const@H_404_2@ INADDR_NONE = 0@H_404_2@xffffffff

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

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

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

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

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

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

    xx := (*ICMP_ECHO_REPLY)(unsafe.Pointer(&ReplyBuffer[0@H_404_2@]))
    fmt.Println(xx)
}
原文链接:https://www.f2er.com/go/187102.html

猜你在找的Go相关文章