Ejemplo n.º 1
0
func main() {
	pid = os.Getpid()
	log.Printf("%d starting", pid)
	a, err := net.ResolveIPAddr("ip4", "127.0.0.1")
	if err != nil {
		log.Panic(err)
	}
	addr = a
	conn, err := net.ListenIP("ip:253", addr)
	if err != nil {
		log.Panic(err)
	}
	buf := make([]byte, 9999)
	i := 0
	lim := 3
	for {
		n, ra, err := conn.ReadFromIP(buf)
		if err != nil {
			log.Panic(err)
		}
		s := string(buf[:n])
		s = strings.TrimSpace(s)
		log.Printf("received from %s: %s", ra.String(), s)
		if i < lim {
			i++
			go send(fmt.Sprintf("%d:%d(%s)", pid, i, s))
		}
	}
}
Ejemplo n.º 2
0
func handlerResolve(w http.ResponseWriter, r *http.Request) {
	lp, err := Localhost()
	if err != nil {
		panic(err)
	}
	ips := lp.String()
	fmt.Println("ip:", ips) // 127.0.0.1

	netaddr, err := net.ResolveIPAddr("ip4", ips)
	if err != nil {
		panic(err)
	}
	fmt.Println("netaddr:", netaddr.String()) // 127.0.0.1

	conn, err := net.ListenIP("ip4:icmp", netaddr)
	if err != nil {
		panic(err)
	}

	buf := make([]byte, 1024)
	num, _, _ := conn.ReadFrom(buf)
	// build and ping localhost with sudo
	fmt.Printf("ReadPacket: %X\n", buf[:num])
	// ReadPacket: 0800FD6729...
}
Ejemplo n.º 3
0
// ListenEcho from routers in path
func ListenEcho(addresses chan string) {
	localAddress, err := net.ResolveIPAddr(ICMP, LocalAddress)
	Check(err)

	c, err := net.ListenIP(ICMP, localAddress)
	Check(err)
	c.SetReadDeadline(time.Now().Add(time.Second * Deadline))
	defer c.Close()

	for {
		buffer := make([]byte, BufferSize)
		bytesRead, remoteAddress, err := c.ReadFromIP(buffer)
		if e, ok := err.(net.Error); ok && e.Timeout() {
			// if err were a timeout we don't raise panic
			c.SetReadDeadline(time.Now().Add(time.Second * Deadline))
			addresses <- ""
			continue
		} else {
			Check(err)
		}

		if bytesRead > 0 {
			addresses <- remoteAddress.String()
		}
	}
}
Ejemplo n.º 4
0
func receiveSynAck(localAddress, remoteAddress string) time.Time {
	netaddr, err := net.ResolveIPAddr("ip4", localAddress)
	if err != nil {
		log.Fatalf("net.ResolveIPAddr: %s. %s\n", localAddress, netaddr)
	}

	conn, err := net.ListenIP("ip4:tcp", netaddr)
	if err != nil {
		log.Fatalf("ListenIP: %s\n", err)
	}
	var receiveTime time.Time
	for {
		buf := make([]byte, 1024)
		numRead, raddr, err := conn.ReadFrom(buf)
		if err != nil {
			log.Fatalf("ReadFrom: %s\n", err)
		}
		if raddr.String() != remoteAddress {
			// this is not the packet we are looking for
			continue
		}
		receiveTime = time.Now()
		//fmt.Printf("Received: % x\n", buf[:numRead])
		tcp := NewTCPHeader(buf[:numRead])
		// Closed port gets RST, open port gets SYN ACK
		if tcp.HasFlag(RST) || (tcp.HasFlag(SYN) && tcp.HasFlag(ACK)) {
			break
		}
	}
	return receiveTime
}
Ejemplo n.º 5
0
// ListenMulticastIPv4 creates a net.IPConn to receive multicast messages for the given group
// address. laddr specifies which network interface to use when joining the group.
func ListenMulticastIPv4(gaddr, laddr net.IP) (*net.IPConn, error) {
	gaddr = gaddr.To4()
	laddr = laddr.To4()
	c, err := net.ListenIP("ip4:112", &net.IPAddr{IP: gaddr})
	if err != nil {
		return nil, err
	}

	f, err := c.File()
	if err != nil {
		return nil, err
	}
	defer f.Close()

	mreq := &syscall.IPMreq{
		Multiaddr: [4]byte{gaddr[0], gaddr[1], gaddr[2], gaddr[3]},
		Interface: [4]byte{laddr[0], laddr[1], laddr[2], laddr[3]},
	}

	err = syscall.SetsockoptIPMreq(int(f.Fd()), syscall.IPPROTO_IP, syscall.IP_ADD_MEMBERSHIP, mreq)
	if err != nil {
		return nil, err
	}

	return c, nil
}
Ejemplo n.º 6
0
// tcp guard
func tcpGuard() {
	conn, err := net.ListenIP("ip4:tcp", &net.IPAddr{IP: serverIp})
	if err != nil {
		logMain(true, err.Error())
	}

	b := make([]byte, 1024)
	var tcp TCPHeader
	for {
		numRead, remoteAddr, err := conn.ReadFromIP(b)
		if err != nil {
			logMain(false, "read from ip:%s", err.Error())
			continue
		}
		NewTCPHeader(b[:numRead], &tcp)
		/*nmap: Page 65 of RFC 793 says that “if the [destination] port state is
		CLOSED .... an incoming segment not containing a RST causes a RST to be
		sent in response.”  Then the next page discusses packets sent to open
		ports without the SYN, RST, or ACK bits set, stating that: “you are
		unlikely to get here, but if you do, drop the segment, and return.”
		*/
		if tcp.HasFlag(RST) || tcp.HasFlag(ACK) {
			continue
		}

		port := int(tcp.Destination)
		ip := remoteAddr.IP
		ipString := ip.String()

		// is exclude port
		if isExlcudePort(port) {
			continue
		}

		// check ignore ip
		if isIgnoredIP(ip) {
			continue
		}

		// if blocked before
		if isBlockedIP(ipString) {
			continue
		}

		// verify port usage
		if smartVerify(port) {
			continue
		}

		logAlarm("attackalert: %s from host: %s to TCP port: %d",
			*reportPacketType(tcp.Ctrl), ipString, port)
		if checkStateEngine(ipString, port) {
			logBlocked("Host: %s Port: %d TCP Blocked", ipString, port)
			// run extern command
			runExternalCommand(ipString, port)
		}
	}
}
Ejemplo n.º 7
0
func main() {
	protocol := "icmp"
	netaddr, _ := net.ResolveIPAddr("ip4", "127.0.0.1")
	conn, _ := net.ListenIP("ip4:"+protocol, netaddr)

	buf := make([]byte, 1024)
	numRead, _, _ := conn.ReadFrom(buf)
	fmt.Printf("% X\n", buf[:numRead])
}
Ejemplo n.º 8
0
func TestIPConnSpecificMethods(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Logf("skipping read test on %q", runtime.GOOS)
		return
	}
	if os.Getuid() != 0 {
		t.Logf("skipping test; must be root")
		return
	}

	la, err := net.ResolveIPAddr("ip4", "127.0.0.1")
	if err != nil {
		t.Fatalf("net.ResolveIPAddr failed: %v", err)
	}
	c, err := net.ListenIP("ip4:icmp", la)
	if err != nil {
		t.Fatalf("net.ListenIP failed: %v", err)
	}
	c.LocalAddr()
	c.RemoteAddr()
	c.SetDeadline(time.Now().Add(100 * time.Millisecond))
	c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	c.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
	c.SetReadBuffer(2048)
	c.SetWriteBuffer(2048)
	defer c.Close()

	id := os.Getpid() & 0xffff
	wb := newICMPEchoRequest(id, 1, 128, []byte("IPCONN TEST "))
	rb := make([]byte, 20+128)
	if _, err := c.WriteToIP(wb, c.LocalAddr().(*net.IPAddr)); err != nil {
		t.Errorf("net.IPConn.WriteToIP failed: %v", err)
		return
	}
	if _, _, err := c.ReadFromIP(rb); err != nil {
		t.Errorf("net.IPConn.ReadFromIP failed: %v", err)
		return
	}
	if _, _, err := c.WriteMsgIP(wb, nil, c.LocalAddr().(*net.IPAddr)); err != nil {
		condErrorf(t, "net.UDPConn.WriteMsgIP failed: %v", err)
		return
	}
	if _, _, _, _, err := c.ReadMsgIP(rb, nil); err != nil {
		condErrorf(t, "net.UDPConn.ReadMsgIP failed: %v", err)
		return
	}

	if f, err := c.File(); err != nil {
		condErrorf(t, "net.IPConn.File failed: %v", err)
		return
	} else {
		f.Close()
	}
}
Ejemplo n.º 9
0
func NewICMPClient(localAddr *net.IPAddr) (*ICMPClient, os.Error) {
	client := new(ICMPClient)
	client.localAddr = localAddr
	conn, e := net.ListenIP("ip4:icmp", localAddr)
	if e != nil {
		fmt.Printf("%s\n", e)
		return nil, e
	}
	client.conn = conn
	return client, nil
}
Ejemplo n.º 10
0
func udpGuard() {
	conn, err := net.ListenIP("ip4:udp", &net.IPAddr{IP: serverIp})
	if err != nil {
		logMain(true, err.Error())
	}

	b := make([]byte, 1024)
	var udp UDPHeader
	for {
		numRead, remoteAddr, err := conn.ReadFromIP(b)
		if err != nil {
			logMain(false, "read from ip:%s", err.Error())
			continue
		}
		NewUDPHeader(b[:numRead], &udp)
		port := int(udp.Destination)

		// ignore noisy port
		if _, ok := cfgNoisyPorts[port]; ok {
			continue
		}

		log.Printf("%v: %d->%d", remoteAddr, udp.Source, udp.Destination)
		ip := remoteAddr.IP
		ipString := ip.String()

		// is exclude port
		if isExlcudePort(port) {
			continue
		}

		// check ignore ip
		if isIgnoredIP(ip) {
			continue
		}

		// if blocked before
		if isBlockedIP(ipString) {
			continue
		}

		// verify port usage
		if smartVerify(port) {
			continue
		}

		logAlarm("attackalert: UDP scan from host: %s to UDP port: %d", ipString, port)
		if checkStateEngine(ipString, port) {
			logBlocked("Host: %s Port: %d UDP Blocked", ipString, port)
			// run extern command
			runExternalCommand(ipString, port)
		}
	}
}
Ejemplo n.º 11
0
func main() {
	name, err := os.Hostname()
	checkError(err)
	ipAddr, err := net.ResolveIPAddr("ipv4", name)
	checkError(err)
	conn, err := net.ListenIP("ip4:ip", ipAddr)
	checkError(err)
	for {
		handleClient(conn)
	}
}
Ejemplo n.º 12
0
func (p *Pinger) listen(netProto string) *net.IPConn {
	conn, err := net.ListenIP(netProto, p.ListenAddr)
	if err != nil {
		p.mu.Lock()
		p.ctx.err = err
		p.mu.Unlock()
		p.debugln("Run(): close(p.ctx.done)")
		close(p.ctx.done)
		return nil
	}
	return conn
}
Ejemplo n.º 13
0
func main() {
	protocol := "icmp"
	netaddr, _ := net.ResolveIPAddr("ip4", "127.0.0.1")
	for {
		conn, _ := net.ListenIP("ip4:"+protocol, netaddr)

		buf := make([]byte, 1024)
		numRead, _, _ := conn.ReadFrom(buf)
		s := string(buf[:numRead])
		fmt.Println(s)
	}
}
Ejemplo n.º 14
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	bcastIP := "127.0.0.1"
	flag.Parse()
	if myID == -1 || nGroup == -1 {
		log.Panic("usage")
	}
	log.Printf("upaxos id(%d) started in group of %d", myID, nGroup)
	defer log.Printf("upaxos id(%d) ending", myID)

	lfr, lfw := logfile(myID)
	promises, accepts, learnings := loadLogData(lfr)
	lfw.Printf("starting %d", myID)

	// begin listening on my well known address
	la, err := net.ResolveIPAddr("ip4", bcastIP)
	if err != nil {
		log.Panic(err)
	}
	conn, err := net.ListenIP(groupIPProto, la)
	if err != nil {
		log.Panic(err)
	}

	sendDest, err = net.ResolveIPAddr("ip4", bcastIP)
	if err != nil {
		log.Panic(err)
	}

	leadc := make(chan Msg)
	acceptc := make(chan Msg)
	learnc := make(chan Msg)
	mainc := make(chan Msg)
	receivers = []chan Msg{leadc, acceptc, learnc, mainc}
	go lead(leadc)
	go accept(acceptc, lfw, promises, accepts)
	go learn(learnc, lfw, learnings)
	go listen(conn)
loop:
	for m := range mainc {
		if len(m.f) > 0 {
			switch m.f[0] {
			case "quit":
				fallthrough
			case "exit":
				fallthrough
			case "bye":
				log.Print("exiting")
				break loop
			}
		}
	}
}
Ejemplo n.º 15
0
func IcmpPing(addr string, timeout time.Duration) (time.Duration, error) {

	raddr, err := net.ResolveIPAddr("ip4", addr) // *IPAddr
	if err != nil {
		return 0, err
	}

	ipconn, err := net.ListenIP("ip4:icmp", nil) // *IPConn (Conn 인터페이스 구현)
	if err != nil {
		return 0, err
	}

	sendid := os.Getpid() & 0xffff
	sendseq := 1
	pingpktlen := 64

	sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte("Go Ping"))

	start := time.Now()

	n, err := ipconn.WriteToIP(sendpkt, raddr)
	if err != nil || n != pingpktlen {
		return 0, err
	}

	ipconn.SetReadDeadline(start.Add(timeout)) // 0.5 second

	resp := make([]byte, 1024)
	for {
		_, _, err := ipconn.ReadFrom(resp)
		//fmt.Printf("%d bytes from %s: icmp_req=%d time=%.2f ms\n", n, dst, sendseq, elapsedTime(start))

		if err != nil {
			return 0, err
		}
		if resp[0] != ICMP_ECHO_REPLY {
			continue
		}
		rcvid, rcvseq := parsePingReply(resp)
		if rcvid != sendid || rcvseq != sendseq {
			return 0, err
		}
		break
	}

	return time.Now().Sub(start), nil
}
Ejemplo n.º 16
0
func main() {
	ipc, err := net.ListenIP("ip4:udp", &net.IPAddr{IP: net.ParseIP("127.0.0.1")})
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	bf := make([]byte, 8192)

	for {
		if n, err := ipc.Read(bf); err != nil {
			fmt.Printf("Error: %v\n", err)
			return
		} else {
			fmt.Printf("Recieve[127.0.0.1]:%v\n", bf[:n])
		}
	}
}
Ejemplo n.º 17
0
func main() {
	la, err := net.ResolveIPAddr("ip4", "127.0.0.1")
	if err != nil {
		log.Panic(err)
	}
	conn, err := net.ListenIP("ip:253", la)
	if err != nil {
		log.Panic(err)
	}
	buf := make([]byte, 9999)
	for {
		n, ra, err := conn.ReadFromIP(buf)
		if err != nil {
			log.Panic(err)
		}
		log.Printf("received from %s: %s", ra.String(), string(buf[:n]))
	}
}
Ejemplo n.º 18
0
func (s *Server) ListenAndServeICMPv6() {
	ipAddr := &net.IPAddr{IP: net.IPv6linklocalallrouters, Zone: "tap" + s.name}
	conn, err := net.ListenIP("ip6:58", ipAddr)
	if err != nil {
		l.Info("error: " + err.Error())
		return
	}
	defer conn.Close()
	if err = bindToDevice(conn, "tap"+s.name); err != nil {
		l.Info("error: " + err.Error())
		return
	}
	s.Lock()
	s.ipv6conn = ipv6.NewPacketConn(conn)
	s.Unlock()

	if err = s.ipv6conn.SetControlMessage(ipv6.FlagDst, true); err != nil {
		l.Info(err.Error())
		return
	}

	buffer := make([]byte, 1500)
	go s.Unsolicitated()

	for {
		select {
		case <-s.done:
			return
		default:
			s.ipv6conn.SetReadDeadline(time.Now().Add(1 * time.Second))
			if _, _, src, err := s.ipv6conn.ReadFrom(buffer); err == nil {
				req := &ICMPv6{}
				if err = req.Unmarshal(buffer); err == nil {
					if req.Type == uint8(ipv6.ICMPTypeRouterSolicitation) {
						s.sendRA(src)
					}
				}
			}
		}
	}
}
Ejemplo n.º 19
0
func main() {
	// Resolve binding address
	netaddr, err := net.ResolveIPAddr("ip6", "::")
	if err != nil {
		log.Fatal("Cannot resolve address\n")
	}
	fmt.Println("Listen on :", netaddr)

	// listen on ICMPv6
	conn, err := net.ListenIP("ip6:58", netaddr)
	if err != nil {
		log.Fatal("Cannot listen raw socket\n")
	}

	buf := make([]byte, 1024)
	for {
		// read data from raw socket
		numRead, addr, _ := conn.ReadFrom(buf)
		fmt.Printf("Read %d bytes from %s\n", numRead, addr)
	}
}
Ejemplo n.º 20
0
func main() {
	//ripa, err := net.ResolveIPAddr("ip", "192.168.135.253")
	ripa, err := net.ResolveIPAddr("ip", "localhost")
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	lp, err1 := net.ListenIP("ip:icmp", ripa)
	if err1 != nil {
		fmt.Printf("Error1: %v\n", err1)
		return
	}
	for {
		buffer := make(myByte, 4096)
		if n, addr, err := lp.ReadFrom(buffer); err != nil {
			fmt.Printf("Error2: %v\n", err)
			return
		} else {
			fmt.Printf("Revieve from %v => %v\n", addr, buffer[:n])
		}

	}
}
Ejemplo n.º 21
0
Archivo: main.go Proyecto: CBiX/fahrrad
func main() {
	var err error
	// create redis connection pool
	if db, err = pool.New("tcp", "localhost:6379", 10); err != nil {
		panic(err)
	}
	defer db.Empty()
	dbc, err := db.Get()
	if err != nil {
		fmt.Println(err)
	}
	for k, v := range defaultConfig {
		dbc.PipeAppend("HSETNX", "fahrrad/config", k, v)
	}
	for k, _ := range defaultConfig {
		dbc.PipeAppend("HGET", "fahrrad/config", k)
	}
	for _, _ = range defaultConfig {
		dbc.PipeResp()
	}
	var v int
	v, err = dbc.PipeResp().Int()
	if err == nil {
		AssignedPrefixLength = uint8(v)
	}
	v, err = dbc.PipeResp().Int()
	if err == nil {
		OnLinkPrefixLength = uint8(v)
	}
	v, err = dbc.PipeResp().Int()
	if err == nil {
		DefaultValidLifetime = uint32(v)
	}
	v, err = dbc.PipeResp().Int()
	if err == nil {
		DefaultPreferredLifetime = uint32(v)
	}
	v, err = dbc.PipeResp().Int()
	if err == nil {
		TickerDelay = time.Duration(v) * time.Second
	}
	defer db.Put(dbc)

	// open listening connection
	conn, err := net.ListenIP("ip6:ipv6-icmp", &net.IPAddr{net.IPv6unspecified, ""})
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	pc = ipv6.NewPacketConn(conn)
	// RFC4861 requires the hop limit set to 255, but the default value in golang is 64
	pc.SetHopLimit(255)

	// only accept neighbor discovery messages
	filter := new(ipv6.ICMPFilter)
	filter.SetAll(true)
	filter.Accept(ipv6.ICMPTypeRouterSolicitation)
	filter.Accept(ipv6.ICMPTypeRouterAdvertisement)
	filter.Accept(ipv6.ICMPTypeNeighborSolicitation)
	filter.Accept(ipv6.ICMPTypeNeighborAdvertisement)
	if err = pc.SetICMPFilter(filter); err != nil {
		panic(err)
	}

	rschan = make(chan routerSolicitation)
	go hostManager()

	// read from socket
	buf := make([]byte, 512)
	for {
		n, _, srcAddr, err := pc.ReadFrom(buf)
		if err != nil {
			panic(err)
		}
		go handleND(srcAddr, buf[:n])
	}
}
Ejemplo n.º 22
0
func (s *Server) ListenAndServeUDPv4() {
	ipAddr := &net.IPAddr{IP: net.IPv4zero}
	conn, err := net.ListenIP("ip4:udp", ipAddr)
	if err != nil {
		l.Info(err.Error())
		return
	}
	defer conn.Close()
	if err = bindToDevice(conn, "tap"+s.name); err != nil {
		l.Info(err.Error())
		return
	}

	s.Lock()
	s.ipv4conn, err = ipv4.NewRawConn(conn)
	s.Unlock()
	if err != nil {
		l.Info(err.Error())
		return
	}

	if err = s.ipv4conn.SetControlMessage(ipv4.FlagDst, true); err != nil {
		l.Warning(err.Error())
		return
	}

	buffer := make([]byte, 1500)

	var gw net.IP
	for _, addr := range s.metadata.Network.IP {
		if addr.Family == "ipv4" && addr.Host == "true" && addr.Gateway == "true" {
			gw = net.ParseIP(addr.Address)
		}
	}
	iface, err := net.InterfaceByName("tap" + s.name)
	if err != nil {
		l.Info(fmt.Sprintf("failed to get iface: %s", err.Error()))
		return
	}

	for {
		select {
		case <-s.done:
			return
		default:
			s.ipv4conn.SetReadDeadline(time.Now().Add(time.Second))
			hdr, _, _, err := s.ipv4conn.ReadFrom(buffer)
			if err != nil {
				switch v := err.(type) {
				case *net.OpError:
					if v.Timeout() {
						continue
					}
				case *net.AddrError:
					if v.Timeout() {
						continue
					}
				case *net.UnknownNetworkError:
					if v.Timeout() {
						continue
					}
				default:
					l.Warning(err.Error())
					return
				}
			}
			var ip4 layers.IPv4
			var udp layers.UDP
			var dhcp4req layers.DHCPv4
			parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &ip4, &udp, &dhcp4req)
			decoded := []gopacket.LayerType{}
			err = parser.DecodeLayers(buffer, &decoded)
			for _, layerType := range decoded {
				switch layerType {
				case layers.LayerTypeDHCPv4:
					if dhcp4req.Operation == layers.DHCP_MSG_REQ {
						dhcp4res, err := s.ServeUDPv4(&dhcp4req)
						if err != nil {
							l.Warning(err.Error())
							continue
						}
						if dhcp4res == nil {
							// ignore empty dhcp packets
							continue
						}

						buf := gopacket.NewSerializeBuffer()
						opts := gopacket.SerializeOptions{true, true}
						gopacket.SerializeLayers(buf, opts,
							&layers.UDP{SrcPort: 67, DstPort: 68},
							dhcp4res)

						wcm := ipv4.ControlMessage{TTL: 255}
						wcm.Dst = net.IPv4bcast.To4()
						wcm.Src = gw.To4()
						wcm.IfIndex = iface.Index
						err = s.ipv4conn.WriteTo(&ipv4.Header{Len: 20, TOS: hdr.TOS, TotalLen: 20 + int(len(buf.Bytes())), FragOff: 0, TTL: 255, Protocol: int(layers.IPProtocolUDP), Src: gw.To4(), Dst: net.IPv4bcast.To4()}, buf.Bytes(), &wcm)
						if err != nil {
							l.Warning(err.Error())
							continue
						}
					} else {
						continue
					}
				}
			}
		}
	}
}
Ejemplo n.º 23
0
func PingPoller(service chan PingRequest) {

	srchost := ""
	for {
		r := <-service
		log.Printf("Received request for %s", r.dsthost)
		var (
			laddr *net.IPAddr
			err   error
		)

		raddr, err := net.ResolveIPAddr("ip", r.dsthost)
		if err != nil {
			log.Println(`net.ResolveIPAddr("%v") = %v, %v`, r.dsthost, raddr, err)
			reply := PingResponse{r.dsthost, -1}
			r.responseChannel <- reply
			continue
		}

		c, err := net.ListenIP("ip4:icmp", laddr)
		if err != nil {
			log.Println(`net.ListenIP("ip4:icmp", %v) = %v, %v`, srchost, c, err)
			reply := PingResponse{r.dsthost, -1}
			r.responseChannel <- reply
			continue
		}

		sendid := os.Getpid() & 0xffff
		const sendseq = 61455
		const pingpktlen = 128
		sendpkt := makePingRequest(sendid, sendseq, pingpktlen, []byte("Go Go Gadget Ping!!!"))

		start := time.Now()
		n, err := c.WriteToIP(sendpkt, raddr)
		if err != nil || n != pingpktlen {
			log.Println(`net.WriteToIP(..., %v) = %v, %v`, raddr, n, err)
			reply := PingResponse{r.dsthost, -1}
			r.responseChannel <- reply
			continue
		}

		c.SetReadDeadline(time.Now().Add(time.Second * 2))
		resp := make([]byte, 1024)
		for {
			n, from, err := c.ReadFrom(resp)
			if err != nil {
				log.Println(`ReadFrom(...) = %v, %v, %v`, n, from, err)
				reply := PingResponse{r.dsthost, -1}
				r.responseChannel <- reply
				break
			}
			if resp[0] != ICMP_ECHO_REPLY {
				continue
			}
			rcvid, rcvseq := parsePingReply(resp)
			end := time.Now()
			if rcvid != sendid || rcvseq != sendseq {
				log.Println(`Ping reply saw id,seq=0x%x,0x%x (expected 0x%x, 0x%x)`, rcvid, rcvseq, sendid, sendseq)
				reply := PingResponse{r.dsthost, -1}
				r.responseChannel <- reply
				break
			}
			log.Println("response took %d nanoseconds.", end.Sub(start))
			reply := PingResponse{r.dsthost, int64(end.Sub(start))}
			r.responseChannel <- reply
			break
		}
		log.Println("saw no ping return")
		reply := PingResponse{r.dsthost, -1}
		r.responseChannel <- reply
	}
}
Ejemplo n.º 24
0
func createICMP4Connection() (*net.IPConn, error) {
	return net.ListenIP("ip4:icmp", &net.IPAddr{IP: net.IPv4zero})
}
Ejemplo n.º 25
0
// IPConn creates a net.IPConn using the given local and remote addresses using IP protocol
// 112 (VRRP).
func IPConn(localAddr, remoteAddr net.IP) (*net.IPConn, error) {
	c, err := net.ListenIP("ip:112", &net.IPAddr{IP: localAddr})
	if err != nil {
		return nil, err
	}

	f, err := c.File()
	if err != nil {
		return nil, err
	}
	defer f.Close()

	ip4 := localAddr.To4()
	switch {
	case ip4 != nil && !remoteAddr.IsMulticast():
		// IPv4 unicast
		// TTL = 255 per VRRP spec
		if err := setsockopt(f, syscall.IPPROTO_IP, syscall.IP_TTL, 255); err != nil {
			return nil, err
		}

	case ip4 != nil && remoteAddr.IsMulticast():
		// IPv4 multicast
		// TTL = 255 per VRRP spec
		if err := setsockopt(f, syscall.IPPROTO_IP, syscall.IP_MULTICAST_TTL, 255); err != nil {
			return nil, err
		}
		// We don't want to receive our own messages.
		if err := setsockopt(f, syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, 0); err != nil {
			return nil, err
		}

	case ip4 == nil && !remoteAddr.IsMulticast():
		// IPv6 unicast
		// HOPLIMIT = 255 per VRRP spec
		if err := setsockopt(f, syscall.IPPROTO_IPV6, syscall.IPV6_UNICAST_HOPS, 255); err != nil {
			return nil, err
		}

	case ip4 == nil && remoteAddr.IsMulticast():
		// IPv6 multicast
		// HOPLIMIT = 255 per VRRP spec
		if err := setsockopt(f, syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_HOPS, 255); err != nil {
			return nil, err
		}
		// We don't want to receive our own messages.
		if err := setsockopt(f, syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_LOOP, 0); err != nil {
			return nil, err
		}

	}

	if ip4 == nil {
		// IPv6 unicast and multicast
		// Request that the ancillary data for received packets include the hop limit and the
		// destination address.

		// TODO(angusc): syscall.IPV6_RECVHOPLIMIT and syscall.IPV6_RECVPKTINFO are prefered but they
		// don't work on lucid.
		if err := setsockopt(f, syscall.IPPROTO_IPV6, syscall.IPV6_2292HOPLIMIT, 1); err != nil {
			return nil, err
		}
		if err := setsockopt(f, syscall.IPPROTO_IPV6, syscall.IPV6_2292PKTINFO, 1); err != nil {
			return nil, err
		}
	}

	log.Infof("ha.IPConn: laddr=%v, raddr=%v", localAddr, remoteAddr)
	return c, nil
}