Example #1
1
func ApiStruct2Peer(p *gobgpapi.Peer) *Peer {
	localCaps := capabilities{}
	remoteCaps := capabilities{}
	for _, buf := range p.Conf.LocalCap {
		c, _ := bgp.DecodeCapability(buf)
		localCaps = append(localCaps, c)
	}
	for _, buf := range p.Conf.RemoteCap {
		c, _ := bgp.DecodeCapability(buf)
		remoteCaps = append(remoteCaps, c)
	}
	remoteIp, _ := net.ResolveIPAddr("ip", p.Conf.NeighborAddress)
	localIp, _ := net.ResolveIPAddr("ip", p.Conf.LocalAddress)
	conf := PeerConf{
		RemoteIp:     remoteIp.String(),
		Id:           net.ParseIP(p.Conf.Id),
		RemoteAs:     p.Conf.PeerAs,
		LocalAs:      p.Conf.LocalAs,
		RemoteCap:    remoteCaps,
		LocalCap:     localCaps,
		PrefixLimits: p.Conf.PrefixLimits,
		LocalIp:      localIp.String(),
		Interface:    p.Conf.NeighborInterface,
	}
	return &Peer{
		Conf:           conf,
		Info:           p.Info,
		Timers:         p.Timers,
		RouteReflector: p.RouteReflector,
		RouteServer:    p.RouteServer,
	}
}
Example #2
0
func matchSubnet(patterns []string, addresses ...string) (bool, bool, error) {
	oneValidPattern := false
	for _, p := range patterns {
		for _, a := range addresses {
			ip, err := net.ResolveIPAddr("ip", a)
			if err != nil {
				errors.Trace(errors.Annotate(err, "could not parse machine's address"))
				continue
			} else if pip, err := net.ResolveIPAddr("ip", p); err == nil {
				oneValidPattern = true
				if ip.IP.Equal(pip.IP) {
					return true, true, nil
				}
			} else if pip := net.ParseIP(p); pip != nil {
				oneValidPattern = true
				if ip.IP.Equal(pip) {
					return true, true, nil
				}
			} else if _, ipNet, err := net.ParseCIDR(p); err == nil {
				oneValidPattern = true
				if ipNet.Contains(ip.IP) {
					return true, true, nil
				}
			}
		}
	}
	return false, oneValidPattern, nil
}
Example #3
0
func initSessions() {
	recvAddr, _ := net.ResolveIPAddr("ip", "127.0.0.1")
	senderAddr, _ = net.ResolveIPAddr("ip", "127.0.0.2")

	// Create a UDP transport with "local" address and use this for a "local" RTP session
	// Not used in these tests, used to initialize and get a Session
	tpRecv, _ := NewTransportUDP(recvAddr, recvPort, localZone)

	// TransportUDP implements RtpTransportWrite and RtpTransportRecv interfaces thus
	// set it in the RtpSession for both interfaces
	rsRecv = NewSession(tpRecv, tpRecv)

	// Create and store the data receive channel.
	dataReceiver = rsRecv.CreateDataReceiveChan()

	// Create a media stream.
	// The SSRC identifies the stream. Each stream has its own sequence number and other
	// context. A RTP session can have several RTP stream for example to send several
	// streams of the same media. Need an output stream to test for collisions/loops
	//
	strIdx, _ := rsRecv.NewSsrcStreamOut(&Address{recvAddr.IP, recvPort, recvPort + 1, localZone}, 0x01020304, 0x4711)
	rsRecv.SsrcStreamOutForIndex(strIdx).SetSdesItem(SdesCname, "AAAAAA")
	rsRecv.SsrcStreamOutForIndex(strIdx).SetPayloadType(0)
	rsRecv.rtcpServiceActive = true // to simulate an active RTCP service

	tpSender, _ := NewTransportUDP(senderAddr, senderPort, remoteZone)
	rsSender = NewSession(tpSender, tpSender)
}
Example #4
0
func TestSet(t *testing.T) {
	t.Parallel()
	hCopy := sample(t)
	one0, err := net.ResolveIPAddr("ip", "10.0.0.1")
	ok(t, err)
	hCopy.Set(*one0, "tendot")
	equals(t, len(hCopy.records), 4)
	equals(t, hCopy.records[3].Hostnames["tendot"], true)
	equals(t, hCopy.records[3].IpAddress.String(), "10.0.0.1")

	// appending same element shouldn't change anything
	hCopy.Set(*one0, "tendot")
	equals(t, len(hCopy.records), 4)

	one92, err := net.ResolveIPAddr("ip", "192.168.3.7")
	ok(t, err)
	hCopy.Set(*one92, "tendot")
	equals(t, hCopy.records[3].IpAddress.String(), "192.168.3.7")

	ip6, err := net.ResolveIPAddr("ip", "::1")
	ok(t, err)
	hCopy.Set(*ip6, "tendot")
	equals(t, len(hCopy.records), 5)
	equals(t, hCopy.records[4].IpAddress.String(), "::1")
}
Example #5
0
func Ping(hostName string, id uint16, sequence uint16, payload []byte) os.Error {

	localAddr, e := net.ResolveIPAddr("0.0.0.0")
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	remoteAddr, e := net.ResolveIPAddr(hostName)
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	cl, e := NewPingClient(localAddr)
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	cl.SendEchoRequest(remoteAddr, id, sequence, payload)
	cl.Close()

	return nil
}
Example #6
0
func (s *store) filterAddr(addrs []string, filter string) ([]string, error) {
	host, port, err := net.SplitHostPort(filter)
	if err != nil {
		return nil, err
	}

	ip, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}

	var joinPeers []string
	for _, addr := range addrs {
		joinHost, joinPort, err := net.SplitHostPort(addr)
		if err != nil {
			return nil, err
		}

		joinIp, err := net.ResolveIPAddr("ip", joinHost)
		if err != nil {
			return nil, err
		}

		// Don't allow joining ourselves
		if ip.String() == joinIp.String() && port == joinPort {
			continue
		}
		joinPeers = append(joinPeers, addr)
	}
	return joinPeers, nil
}
Example #7
0
func TestProtocols(t *testing.T) {
	t.Parallel()
	one92, _ := net.ResolveIPAddr("ip", "192.168.3.7")
	ip6, _ := net.ResolveIPAddr("ip", "::1")
	equals(t, matchProtocols(one92.IP, ip6.IP), false)
	equals(t, matchProtocols(one92.IP, one92.IP), true)
	equals(t, matchProtocols(ip6.IP, ip6.IP), true)
}
Example #8
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
			}
		}
	}
}
Example #9
0
func dialTCP(target string, w http.ResponseWriter, module Module) (net.Conn, error) {
	var dialProtocol, fallbackProtocol string

	dialer := &net.Dialer{Timeout: module.Timeout}
	if module.TCP.Protocol == "" {
		module.TCP.Protocol = "tcp"
	}
	if module.TCP.Protocol == "tcp" && module.TCP.PreferredIpProtocol == "" {
		module.TCP.PreferredIpProtocol = "ip6"
	}
	if module.TCP.PreferredIpProtocol == "ip6" {
		fallbackProtocol = "ip4"
	} else {
		fallbackProtocol = "ip6"
	}

	dialProtocol = module.TCP.Protocol
	if module.TCP.Protocol == "tcp" {
		target_address, _, err := net.SplitHostPort(target)
		ip, err := net.ResolveIPAddr(module.TCP.PreferredIpProtocol, target_address)
		if err != nil {
			ip, err = net.ResolveIPAddr(fallbackProtocol, target_address)
			if err != nil {
				return nil, err
			}
		}

		if ip.IP.To4() == nil {
			dialProtocol = "tcp6"
		} else {
			dialProtocol = "tcp4"
		}
	}

	if dialProtocol == "tcp6" {
		fmt.Fprintf(w, "probe_ip_protocol 6\n")
	} else {
		fmt.Fprintf(w, "probe_ip_protocol 4\n")
	}

	if !module.TCP.TLS {
		return dialer.Dial(dialProtocol, target)
	}
	config, err := module.TCP.TLSConfig.GenerateConfig()
	if err != nil {
		return nil, err
	}
	return tls.DialWithDialer(dialer, dialProtocol, target, config)
}
Example #10
0
func (i *siNetIFInfo) UnmarshalJSON(data []byte) (err error) {
	var tmp struct {
		Metric      int    `json:"metric"`
		MTU         int    `json:"mtu"`
		Flags       int    `json:"flags"`
		Type        string `json:"type"`
		Name        string `json:"name"`
		Broadcast   string `json:"broadcast"`
		Address     string `json:"address"`
		Address6    string `json:"address6"`
		HWAddr      string `json:"hwaddr"`
		Destination string `json:"destination"`
		Netmask     string `json:"netmask"`
	}
	err = json.Unmarshal(data, &tmp)
	if err != nil {
		return
	}

	i.Metric = tmp.Metric
	i.MTU = tmp.MTU
	i.Flags = tmp.Flags
	i.Type = tmp.Type
	i.Name = tmp.Name

	i.Broadcast, err = net.ResolveIPAddr("ip", tmp.Broadcast)
	if err != nil {
		return
	}
	i.Address, err = net.ResolveIPAddr("ip", tmp.Address)
	if err != nil {
		return
	}
	i.Address6, err = net.ResolveIPAddr("ip", tmp.Address6)
	if err != nil {
		return
	}
	i.HWAddr, err = net.ParseMAC(tmp.HWAddr)
	if err != nil {
		return
	}
	i.Destination, err = net.ResolveIPAddr("ip", tmp.Destination)
	if err != nil {
		return
	}
	i.Netmask = net.IPMask(net.ParseIP(tmp.Netmask))
	return
}
Example #11
0
func udpAddrFromString(addr string) *net.UDPAddr {
	host, portStr, err := net.SplitHostPort(addr)
	if err != nil {
		log.Fatal("Bad StatsD listening address", addr)
	}

	if host == "" {
		host = "0.0.0.0"
	}
	ip, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		log.Fatalf("Unable to resolve %s: %s", host, err)
	}

	port, err := strconv.Atoi(portStr)
	if err != nil || port < 0 || port > 65535 {
		log.Fatalf("Bad port %s: %s", portStr, err)
	}

	return &net.UDPAddr{
		IP:   ip.IP,
		Port: port,
		Zone: ip.Zone,
	}
}
Example #12
0
func (resolver *addressResolver) ResolveIP(host string) (net.IP, error) {
	if host == "localhost" || host == "127.0.0.1" {
		if resolver.local != nil {
			return resolver.local, nil
		}
		if !resolver.checked {
			resolver.checked = true
			devices, err := net.Interfaces()
			if err != nil {
				return nil, err
			}
			for _, dev := range devices {
				if (dev.Flags&net.FlagUp != 0) && (dev.Flags&net.FlagLoopback == 0) {
					addrs, err := dev.Addrs()
					if err != nil {
						continue
					}
					for i := range addrs {
						if ip, ok := addrs[i].(*net.IPNet); ok {
							log.Printf("Using %v for %s", ip, host)
							resolver.local = ip.IP
							return resolver.local, nil
						}
					}
				}
			}
		}
	}
	addr, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}
	return addr.IP, nil
}
Example #13
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
}
Example #14
0
// NewPingChecker returns a check function that can check if a host answer to a ICMP Ping
func NewPingChecker(host, service, ip string) CheckFunction {
	return func() Event {
		var retRtt time.Duration
		var result = Event{Host: host, Service: service, State: "critical"}

		p := fastping.NewPinger()
		p.MaxRTT = maxPingTime
		ra, err := net.ResolveIPAddr("ip4:icmp", ip)
		if err != nil {
			result.Description = err.Error()
		}

		p.AddIPAddr(ra)
		p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
			result.State = "ok"
			result.Metric = float32(retRtt.Nanoseconds() / 1e6)
		}

		err = p.Run()
		if err != nil {
			result.Description = err.Error()
		}
		return result
	}
}
Example #15
0
func Ping(timeout int) {
	log.SetPrefix("[Ping] ")
	scanner := bufio.NewScanner(os.Stdin)

	ips := make([]string, 0)
	var input string
	// single ip
	for scanner.Scan() {
		input = scanner.Text()
		_, err := net.ResolveIPAddr("ip", input)
		if err != nil {
			break
		} else {
			ips = append(ips, input)
		}
	}
	// whole lan
	if strings.Contains(input, "/") {
		lastDotIdx := strings.LastIndex(input, ".")
		ipPre := input[:lastDotIdx+1]
		for i := 0; i < 256; i++ {
			ip := ipPre + strconv.Itoa(i)
			ips = append(ips, ip)
		}
	}

	runFastPing(ips, "", timeout)
	runFastPing(ips, "127.0.0.1", timeout)

}
Example #16
0
func Resolve(name string) (net.IP, error) {
	addr, err := net.ResolveIPAddr("ip", name)
	if err != nil {
		return nil, err
	}
	return addr.IP, err
}
Example #17
0
func (d DNSResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
	addr, err := net.ResolveIPAddr("ip", name)
	if err != nil {
		return ctx, nil, err
	}
	return ctx, addr.IP, err
}
Example #18
0
func dial(spec string) (*net.TCPConn, error) {
	host, port, err := net.SplitHostPort(spec)
	if err != nil {
		log.Infof("dial(): ERR: could not extract host and port from spec %v: %v", spec, err)
		return nil, err
	}
	remoteAddr, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		log.Infof("dial(): ERR: could not resolve %v: %v", host, err)
		return nil, err
	}
	portInt, err := strconv.Atoi(port)
	if err != nil {
		log.Infof("dial(): ERR: could not convert network port from string \"%s\" to integer: %v", port, err)
		return nil, err
	}
	remoteAddrAndPort := &net.TCPAddr{IP: remoteAddr.IP, Port: portInt}
	var localAddr *net.TCPAddr
	localAddr = nil
	conn, err := net.DialTCP("tcp", localAddr, remoteAddrAndPort)
	if err != nil {
		log.Infof("dial(): ERR: could not connect to %v:%v: %v", remoteAddrAndPort.IP, remoteAddrAndPort.Port, err)
	}
	return conn, err
}
Example #19
0
// 一个接口上的所有ip4地址
func addrsOfOneInterface(iface net.Interface) (addrs []*net.IPAddr) {
	ifaddrs, err := iface.Addrs()

	if (err != nil) || (len(ifaddrs) == 0) {
		return
	}

	for _, ifaddr := range ifaddrs {
		var ip net.IP
		switch v := ifaddr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		default:
			continue
		}
		if ip.IsLoopback() {
			return
		}
		ip = ip.To4()
		if ip != nil {
			addr, _ := net.ResolveIPAddr("ip", ip.String())
			addrs = append(addrs, addr)
		}
	}
	return
}
Example #20
0
func parseRestrictAddr(relativeTo *net.TCPAddr) error {
	if userRestrictAddr == "" {
		return nil
	}

	realNet := "ip"
	switch len(relativeTo.IP) {
	default:
		// Someone's invented IPv8.  Just hope for the best; if we get an address that doesn't match
		// the listening family at all, then no connections will be accepted.
	case net.IPv4len:
		realNet = "ip4"
	case net.IPv6len:
		// Sometimes net.IP stores IPv4 addresses in 16-byte slices too.  Sigh.
		if bytes.HasPrefix(relativeTo.IP, ipv4MappedPrefix) {
			realNet = "ip4"
		} else {
			realNet = "ip6"
		}
	}

	// This does not propagate IPv6 scopes; the user must specify the same scope explicitly both times
	// if needed.
	ip, err := net.ResolveIPAddr(realNet, userRestrictAddr)
	if err != nil {
		return err
	}

	log.Info("restricting to connections from %v", ip)
	restrictIP = ip
	return nil
}
Example #21
0
func main() {
	var m = flag.Int("m", traceroute.DEFAULT_MAX_HOPS, `Set the max time-to-live (max number of hops) used in outgoing probe packets (default is 64)`)
	var q = flag.Int("q", 1, `Set the number of probes per "ttl" to nqueries (default is one probe).`)

	flag.Parse()
	host := flag.Arg(0)
	options := traceroute.TracerouteOptions{}
	options.SetRetries(*q - 1)
	options.SetMaxHops(*m + 1)

	ipAddr, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return
	}

	fmt.Printf("traceroute to %v (%v), %v hops max, %v byte packets\n", host, ipAddr, options.MaxHops(), options.PacketSize())

	c := make(chan traceroute.TracerouteHop, 0)
	go func() {
		for {
			hop, ok := <-c
			if !ok {
				fmt.Println()
				return
			}
			printHop(hop)
		}
	}()

	_, err = traceroute.Traceroute(host, &options, c)
	if err != nil {
		fmt.Printf("Error: ", err)
	}
}
Example #22
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...
}
Example #23
0
File: pingd.go Project: hizel/pingd
func Post(w rest.ResponseWriter, r *rest.Request) {
	host := Host{}
	err := r.DecodeJsonPayload(&host)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if host.Id == "" {
		rest.Error(w, "id required", 400)
		return
	}
	if host.Address == "" {
		rest.Error(w, "address required", 400)
		return
	}
	ra, err := net.ResolveIPAddr("ip4:icmp", host.Address)
	if err != nil {
		rest.Error(w, err.Error(), 400)
		return
	}
	lock.Lock()
	q := make(chan bool, 1) // chan for stop ping
	store[host.Id] = &HostStore{
		host,
		time.Now(),
		0.0, 0.0, 0.0, 0.0,
		0,
		ring.New(DefCircleLen),
		q}
	go ping(host.Id, ra, time.Second*DefRTT, q, &lock, store)
	lock.Unlock()
	w.WriteJson(&host)
}
Example #24
0
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')
	}
}
Example #25
0
func newDialerAddr(network, addr string) net.Addr {
	netaddr, err := net.ResolveIPAddr(network, addr)
	if err == nil {
		return netaddr
	}
	return fallbackAddr{network, addr}
}
Example #26
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()
		}
	}
}
Example #27
0
func GetRegion(server string) (string, string) {
	if config.Constants.GeoIP == "" {
		return "", ""
	}

	arr := strings.Split(server, ":")
	addr, err := net.ResolveIPAddr("ip4", arr[0])
	if err != nil {
		helpers.Logger.Error(err.Error())
		return "", ""

	}

	record, err := geodb.Country(addr.IP)
	if err != nil {
		helpers.Logger.Error(err.Error())
		return "", ""
	}

	if record.Country.Names["en"] == "Russia" {
		return "ru", "Russia"
	}

	return strings.ToLower(record.Continent.Code), record.Continent.Names["en"]
}
Example #28
0
func NewRtpClient(listenIP string, listenPort int) (*RtpClient, error) {
	localAddr, err := net.ResolveIPAddr("ip", listenIP)
	if err != nil {
		return nil, err
	}
	rtpTransport, err := rtp.NewTransportUDP(localAddr, listenPort)
	if err != nil {
		return nil, err
	}
	session := rtp.NewSession(rtpTransport, rtpTransport)
	err = session.StartSession()
	if err != nil {
		return nil, err
	}

	client := &RtpClient{
		listenPort:   listenPort,
		ReceiveStats: stats.NewStats("RTP received"),
		MissedStats:  stats.NewStats("RTP missed"),
		CtrlStats:    stats.NewStats("RTCP events"),
		RtpSession:   session,
		ctrlChan:     session.CreateCtrlEventChan(rtpCtrlBuffer),
		dataChan:     session.CreateDataReceiveChan(rtpDataBuffer),
		stopped:      golib.NewOneshotCondition(),
	}

	client.wg.Add(1)
	go client.handleCtrlEvents()
	client.wg.Add(1)
	go client.handleDataPackets()

	return client, nil
}
Example #29
0
// Resolve given hostname/address in the given address family
func resolveName(dest string, af string) (net.IP, error) {
	addr, err := net.ResolveIPAddr(af, dest)
	if err != nil {
		return nil, err
	}
	return addr.IP, nil
}
Example #30
0
// Pinguntil will send ICMP echo packets to the destination until the counter is reached, or forever if the counter is set to 0.
// The replies are given in the Response format.
// You can also adjust the delay between two ICMP echo packets with the variable delay.
func Pinguntil(destination string, count int, response chan Response, delay time.Duration) {
	raddr, err := net.ResolveIPAddr("ip", destination)
	if err != nil {
		response <- Response{Delay: 0, Error: err, Destination: destination, Seq: 0}
		close(response)
		return
	}

	ipconn, err := net.Dial("ip:icmp", raddr.IP.String())
	if err != nil {
		response <- Response{Delay: 0, Error: err, Destination: raddr.IP.String(), Seq: 0}
		close(response)
		return
	}

	sendid := os.Getpid() & 0xffff
	pingpktlen := 64
	seq := 0
	var elapsed time.Duration = 0

	for ; seq < count || count == 0; seq++ {
		elapsed = 0
		if seq > 65535 { // The two bytes for seq. Don't overflow!
			seq = 0
		}
		sendpkt := makePingRequest(sendid, seq, pingpktlen, []byte("Go Ping"))

		start := time.Now()

		writesize, err := ipconn.Write(sendpkt)
		if err != nil || writesize != pingpktlen {
			response <- Response{Delay: 0, Error: err, Destination: raddr.IP.String(), Seq: seq, Writesize: writesize, Readsize: 0}
			time.Sleep(delay)
			continue
		}

		ipconn.SetReadDeadline(time.Now().Add(time.Second * 1)) // 1 second

		resp := make([]byte, 1024)
		for {
			readsize, err := ipconn.Read(resp)

			elapsed = time.Now().Sub(start)

			rid, rseq, rcode := parsePingReply(resp)

			if err != nil {
				response <- Response{Delay: 0, Error: err, Destination: raddr.IP.String(), Seq: seq, Writesize: writesize, Readsize: readsize}
				break
			} else if rcode != ICMP_ECHO_REPLY || rseq != seq || rid != sendid {
				continue
			} else {
				response <- Response{Delay: elapsed, Error: err, Destination: raddr.IP.String(), Seq: seq, Writesize: writesize, Readsize: readsize}
				break
			}
		}
		time.Sleep(delay - elapsed)
	}
	close(response)
}