本文整理汇总了Golang中net.DialIP函数的典型用法代码示例。如果您正苦于以下问题:Golang DialIP函数的具体用法?Golang DialIP怎么用?Golang DialIP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DialIP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
var (
icmp ICMP
laddr net.IPAddr = net.IPAddr{IP: net.ParseIP("192.168.34.125")}
raddr net.IPAddr = net.IPAddr{IP: net.ParseIP("114.114.114.114")}
)
conn, err := net.DialIP("ip4:icmp", &laddr, &raddr)
if err != nil {
fmt.Println(err.Error())
return
}
defer conn.Close()
icmp.Type = 8 //8->echo message 0->reply message
icmp.Code = 0
icmp.Checksum = 0
icmp.Identifier = 0
icmp.SequenceNum = 0
var (
buffer bytes.Buffer
)
binary.Write(&buffer, binary.BigEndian, icmp)
icmp.Checksum = CheckSum(buffer.Bytes())
buffer.Reset()
binary.Write(&buffer, binary.BigEndian, icmp)
if _, err := conn.Write(buffer.Bytes()); err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("send icmp packet success!")
}
示例2: Ping
// Ping public method
func Ping(ip string) (bool, error) {
recv := make([]byte, 1024) //保存响应数据
raddr, err := net.ResolveIPAddr("ip", ip) //raddr为目标主机的地址
if err != nil {
fmt.Spintf("resolve ip: %s fail:", ip)
return false, err
}
laddr := net.IPAddr{IP: net.ParseIP("0.0.0.0")} //源地址
if ip == "" {
return false, errors.New("ip or domain is null")
}
conn, err := net.DialIP("ip4:icmp", &laddr, raddr)
if err != nil {
glog.Errorf("dial ip: %s fail:%v", laddr, err)
return false, err
}
defer conn.Close()
buffer := assemblyIcmp()
if _, err := conn.Write(buffer.Bytes()); err != nil {
fmt.Spintf("post Icmp fail: %v", err)
return false, err
}
conn.SetReadDeadline((time.Now().Add(time.Second * 5)))
_, err = conn.Read(recv)
if err != nil {
fmt.Spintf("get Icmp fail: %v", err)
return false, nil
}
return true, nil
}
示例3: ping
func ping(host string, timeLimit int) (re PingReturn) {
re.success = false
re.host = host
PingLogger.Println("Ping ", host)
raddr, err := net.ResolveIPAddr("ip", host)
if err != nil {
PingLogger.Println("resolve ip addr error", err)
re.msg = "ip error"
re.err = err
return
} else {
PingLogger.Println("IP:", raddr)
}
conn, err := net.DialIP("ip4:icmp", nil, raddr)
if err != nil {
if strings.Index(err.Error(), "operation not permitted") != -1 {
log.Fatalln("operation not permitted, please run it by sudo")
}
fmt.Printf("%+v\n", err.Error())
PingLogger.Println(err)
re.msg = "dial error"
re.err = err
return
}
var icmp ICMP
icmp.Type = 8
icmp.Code = 0
icmp.Checksum = 0
icmp.Identifier = 0
icmp.SequenceNum = 0
var buffer bytes.Buffer
binary.Write(&buffer, binary.BigEndian, icmp)
icmp.Checksum = CheckSum(buffer.Bytes())
buffer.Reset()
binary.Write(&buffer, binary.BigEndian, icmp)
PingLogger.Println("Runing Ping data ",
printByte(buffer.Bytes()))
conn.Write(buffer.Bytes())
t_start := time.Now()
conn.SetReadDeadline((time.Now().Add(
time.Duration(timeLimit) * time.Millisecond)))
recv := make([]byte, 100)
recv_len, err := conn.Read(recv)
if err != nil {
re.msg = "read error"
re.err = err
PingLogger.Println(err)
return
}
PingLogger.Println("Recv data ", printByte(recv[:recv_len]))
t_end := time.Now()
dur := t_end.Sub(t_start).Nanoseconds() / 1e6
PingLogger.Println("Time spend ms", dur)
PingLogger.Println("")
re.success = true
defer conn.Close()
return
}
示例4: dialIP
func dialIP(conn *LocalConnection) (*net.IPConn, error) {
ipLocalAddr, err := ipAddr(conn.TCPConn.LocalAddr())
if err != nil {
return nil, err
}
ipRemoteAddr, err := ipAddr(conn.TCPConn.RemoteAddr())
if err != nil {
return nil, err
}
ipSocket, err := net.DialIP("ip4:UDP", ipLocalAddr, ipRemoteAddr)
if err != nil {
return nil, err
}
f, err := ipSocket.File()
if err != nil {
return nil, err
}
defer f.Close()
fd := int(f.Fd())
// This Makes sure all packets we send out have DF set on them.
err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_MTU_DISCOVER, syscall.IP_PMTUDISC_DO)
if err != nil {
return nil, err
}
return ipSocket, nil
}
示例5: main
func main() {
flag.Parse()
if ipAddr == "(none)" || ipProto == -1 {
log.Panic("usage")
}
ra, err := net.ResolveIPAddr("ip4", ipAddr)
if err != nil {
log.Panic(err)
}
proto := fmt.Sprintf("ip:%d", ipProto)
conn, err := net.DialIP(proto, nil, ra)
if err != nil {
log.Panic(err)
}
defer conn.Close()
in := bufio.NewReader(os.Stdin)
line, err := in.ReadSlice('\n')
for err == nil {
_, err = conn.Write([]byte(line))
if err != nil {
log.Panic(err)
}
line, err = in.ReadSlice('\n')
}
}
示例6: sendIPPacket
func sendIPPacket() {
fmt.Println("go!")
ipaddr, err := net.ResolveIPAddr("ip", "192.168.1.254")
if err != nil {
fmt.Println("IP address is wrong!")
return
}
localAddrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println("Local interface is null!")
return
}
lIPAddrs := getSendLocalIP(localAddrs, ipaddr)
if lIPAddrs == nil {
fmt.Println("Local interface is null!")
return
}
fmt.Println(lIPAddrs.String())
ipConn, err := net.DialIP("ip", &net.IPAddr{IP: lIPAddrs.IP, Zone: ""}, ipaddr)
if err != nil {
fmt.Println(err.Error())
return
}
b := []byte{0xAA, 0xBB, 0xCC}
_, err = ipConn.Write(b)
if err != nil {
fmt.Println(err.Error())
return
}
defer ipConn.Close()
}
示例7: dial
func (sender *udpSenderDF) dial() error {
if sender.socket != nil {
if err := sender.socket.Close(); err != nil {
return err
}
sender.socket = nil
}
laddr := &net.IPAddr{IP: sender.localIP}
raddr := &net.IPAddr{IP: sender.remoteIP}
s, err := net.DialIP("ip4:UDP", laddr, raddr)
f, err := s.File()
if err != nil {
return err
}
defer f.Close()
// This makes sure all packets we send out have DF set on them.
err = syscall.SetsockoptInt(int(f.Fd()), syscall.IPPROTO_IP, syscall.IP_MTU_DISCOVER, syscall.IP_PMTUDISC_DO)
if err != nil {
return err
}
sender.socket = s
return nil
}
示例8: singleping
func singleping(ip string) (time.Duration, error) {
addr := net.IPAddr{IP: net.ParseIP(ip)}
sendid := os.Getpid() & 0xffff
sendseq := 1
pingpktlen := 64
sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte("Go Ping"))
ipconn, err := net.DialIP("ip4:icmp", nil, &addr) // *IPConn (Conn 인터페이스 구현)
if err != nil {
log.Fatalf(`net.DialIP("ip4:icmp", %v) = %v`, ipconn, err)
}
ipconn.SetDeadline(time.Now().Add(time.Second)) //1 Second timeout
start := time.Now()
n, err := ipconn.WriteToIP(sendpkt, &addr)
if err != nil || n != pingpktlen {
log.Fatalf(`net.WriteToIP(..., %v) = %v, %v`, addr, n, err)
}
resp := make([]byte, 1024)
_, _, pingerr := ipconn.ReadFrom(resp)
if pingerr != nil {
fmt.Printf("%s : FAIL\n", ip)
} else {
fmt.Printf("%s : %s\n", ip, time.Since(start))
}
// log.Printf("%x", resp)
return time.Since(start), pingerr
}
示例9: main
func main() {
flag.Parse()
dst := flag.Arg(0)
//dst := "121.254.177.105"
raddr, err := net.ResolveIPAddr("ip4", dst) // *IPAddr
if err != nil {
log.Fatalf(`net.ResolveIPAddr("ip4", %v") = %v, %v`, dst, raddr, err)
}
ipconn, err := net.DialIP("ip4:icmp", nil, raddr) // *IPConn (Conn 인터페이스 구현)
if err != nil {
log.Fatalf(`net.DialIP("ip4:icmp", %v) = %v`, ipconn, err)
}
sendid := os.Getpid() & 0xffff
sendseq := 1
pingpktlen := 64
for {
sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte("Go Ping"))
//fmt.Printf("%v, %v\n", sendpkt[0:8], string(sendpkt[8:]))
start := time.Now().UnixNano()
n, err := ipconn.WriteToIP(sendpkt, raddr)
if err != nil || n != pingpktlen {
log.Fatalf(`net.WriteToIP(..., %v) = %v, %v`, raddr, n, err)
}
//ipconn.SetTimeout(5e8) // 0.5 second
resp := make([]byte, 1024)
for {
n, from, err := ipconn.ReadFrom(resp)
fmt.Printf("%d bytes from %s: icmp_req=%d time=%.2f ms\n", n, dst, sendseq, elapsedTime(start))
// log.Printf("%x", resp)
if err != nil {
log.Fatalf(`ReadFrom(...) = %v, %v, %v`, n, from, err)
}
if resp[0] != ICMP_ECHO_REPLY {
continue
}
rcvid, rcvseq := parsePingReply(resp)
if rcvid != sendid || rcvseq != sendseq {
log.Fatalf(`Ping reply saw id,seq=0x%x,0x%x (expected 0x%x, 0x%x)`, rcvid, rcvseq, sendid, sendseq)
}
break
}
sendseq++
time.Sleep(1e9) // 1 second. like -i (interval) option
}
}
示例10: send
func send(s string) {
log.Printf("sending to %s: %s", addr.String(), s)
conn, err := net.DialIP(groupIPProto, nil, addr)
if err != nil {
log.Panic(err)
}
defer conn.Close()
n, err := conn.Write([]byte(s))
if err != nil {
log.Panic(err)
}
log.Printf("sent %d bytes", n)
}
示例11: main
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host", os.Args[0])
os.Exit(1)
}
dst := os.Args[1]
raddr, err := net.ResolveIPAddr("ip4", dst)
checkError(err)
ipconn, err := net.DialIP("ip4:icmp", nil, raddr)
checkError(err)
sendid := os.Getpid() & 0xffff
sendseq := 1
pingpktlen := 64
for {
sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte(""))
start := int64(time.Now().Nanosecond())
_, err := ipconn.WriteToIP(sendpkt, raddr)
checkError(err)
resp := make([]byte, 1024)
for {
n, from, err := ipconn.ReadFrom(resp)
checkError(err)
fmt.Printf("%d bytes from %s: icmp_req = %d time = %.2f ms\n", n,
from, sendseq, elapsedTime(start))
if resp[0] != ICMP_ECHO_REPLY {
continue
}
rcvid, rcvseq := parsePingReply(resp)
if rcvid != sendid || rcvseq != sendseq {
fmt.Println("Ping reply saw id ", rcvid, rcvseq, sendid, sendseq)
}
break
}
if sendseq == 4 {
break
} else {
sendseq++
}
time.Sleep(1e9)
}
}
示例12: main
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s hostname\n", os.Args[0])
os.Exit(1)
}
addr, err := net.ResolveIPAddr("ip", os.Args[1])
if err != nil {
fmt.Printf("Resolution error: %s\n", err.Error())
os.Exit(1)
}
conn, err := net.DialIP("ip4:icmp", addr, addr)
checkError(err)
var msg [512]byte
msg[0] = 8 // echo
msg[1] = 0 // code 0
msg[2] = 0 // checksum, fix later
msg[3] = 0 // checksum, fix later
msg[4] = 0 // identifier[0]
msg[5] = 13 // identifier[1]
msg[6] = 0 // sequence[0]
msg[7] = 37 // sequence[1]
len := 8
check := checkSum(msg[0:len])
msg[2] = byte(check >> 8)
msg[3] = byte(check & 255)
_, err = conn.Write(msg[0:len])
checkError(err)
_, err = conn.Read(msg[0:])
checkError(err)
fmt.Println("Got response")
if msg[5] == 13 {
fmt.Println("Identifier matches")
}
if msg[7] == 37 {
fmt.Println("Sequence matches")
}
os.Exit(0)
}
示例13: TestPing
func TestPing(t *testing.T) {
fmt.Println("flag args: ", flag.Args())
if address == "" {
t.Error("address is empty")
os.Exit(1)
}
fmt.Println("address is ", address)
addr, err := net.ResolveIPAddr("ip", address)
if err != nil {
fmt.Println("Resolution error", err.Error())
os.Exit(1)
}
conn, err := net.DialIP("ip4:icmp", addr, addr)
checkError(err)
var msg [512]byte
msg[0] = 8 // echo
msg[1] = 0 // code 0
msg[2] = 0 // checksum, fix later
msg[3] = 0 // checksum, fix later
msg[4] = 0 // identifier[0]
msg[5] = 13 //identifier[1]
msg[6] = 0 // sequence[0]
msg[7] = 37 // sequence[1]
len := 8
check := checkSum(msg[0:len])
msg[2] = byte(check >> 8)
msg[3] = byte(check & 255)
_, err = conn.Write(msg[0:len])
checkError(err)
_, err = conn.Read(msg[0:])
checkError(err)
fmt.Println("Got response")
if msg[5] == 13 {
fmt.Println("identifier matches")
}
if msg[7] == 37 {
fmt.Println("Sequence matches")
}
os.Exit(0)
}
示例14: dialAddr
func dialAddr(net, addr string, addri netpkg.Addr) (c netpkg.Conn, err error) {
switch ra := addri.(type) {
case *netpkg.TCPAddr:
c, err = netpkg.DialTCP(net, nil, ra)
case *netpkg.UDPAddr:
c, err = netpkg.DialUDP(net, nil, ra)
case *netpkg.IPAddr:
c, err = netpkg.DialIP(net, nil, ra)
default:
err = errors.New("Unknown network address type")
}
if err != nil {
return nil, err
}
return
}
示例15: send
func send(s string) {
if nSent > maxSends {
log.Printf("sends capped at %d; not sending %s", maxSends, s)
return
}
atomic.AddInt32(&nSent, 1)
log.Printf("%20s to %s: %s", "SEND", sendDest.String(), s)
conn, err := net.DialIP(groupIPProto, nil, sendDest)
if err != nil {
log.Panic(err)
}
defer conn.Close()
_, err = conn.Write([]byte(s))
if err != nil {
log.Panic(err)
}
}