当前位置: 首页>>代码示例>>Golang>>正文


Golang syscall.Recvfrom函数代码示例

本文整理汇总了Golang中syscall.Recvfrom函数的典型用法代码示例。如果您正苦于以下问题:Golang Recvfrom函数的具体用法?Golang Recvfrom怎么用?Golang Recvfrom使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Recvfrom函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: readRAWSocket

func (t *Listener) readRAWSocket() {
	// AF_INET can't capture outgoing packets, must change to use AF_PACKET
	// https://github.com/golang/go/issues/7653
	// http://www.binarytides.com/packet-sniffer-code-in-c-using-linux-sockets-bsd-part-2/
	proto := (syscall.ETH_P_ALL<<8)&0xff00 | syscall.ETH_P_ALL>>8 // change to Big-Endian order
	fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, proto)
	if err != nil {
		log.Fatal("socket: ", err)
	}
	defer syscall.Close(fd)
	if t.addr != "" && t.addr != "0.0.0.0" {
		ifi, err := net.InterfaceByName(t.addr)
		if err != nil {
			log.Fatal("interfacebyname: ", err)
		}
		lla := syscall.SockaddrLinklayer{Protocol: uint16(proto), Ifindex: ifi.Index}
		if err := syscall.Bind(fd, &lla); err != nil {
			log.Fatal("bind: ", err)
		}
	}

	var src_ip string
	var dest_ip string
	buf := make([]byte, 65536)

	for {
		n, _, err := syscall.Recvfrom(fd, buf, 0)
		if err != nil {
			log.Println("Error:", err)
			continue
		}
		if n <= 0 {
			continue
		}

		packet := gopacket.NewPacket(buf[:n], layers.LayerTypeEthernet, gopacket.Default)
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			tcp, _ := tcpLayer.(*layers.TCP)

			src_ip = packet.NetworkLayer().NetworkFlow().Src().String()
			dest_ip = packet.NetworkLayer().NetworkFlow().Dst().String()

			t.parsePacket(src_ip, dest_ip, tcp)
		}

	}

}
开发者ID:xxoxx,项目名称:httpcap,代码行数:48,代码来源:listener_linux.go

示例2: readAllEvents

func (w *Watcher) readAllEvents() {
	buf := make([]byte, syscall.Getpagesize())

	listener, _ := w.listener.(*netlinkListener)

	for {
		if w.isDone() {
			return
		}

		nr, _, err := syscall.Recvfrom(listener.sock, buf, 0)

		if err != nil {
			w.Error <- err
			continue
		}
		if nr < syscall.NLMSG_HDRLEN {
			w.Error <- syscall.EINVAL
			continue
		}

		msgs, _ := syscall.ParseNetlinkMessage(buf[:nr])

		for _, m := range msgs {
			if m.Header.Type == syscall.NLMSG_DONE {
				w.handleEventAll(m.Data)
			}
		}
	}
}
开发者ID:cloudimmunity,项目名称:pdiscover,代码行数:30,代码来源:pevents_linux.go

示例3: ReadFrom

func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
	fd.rio.Lock()
	defer fd.rio.Unlock()
	if err := fd.incref(false); err != nil {
		return 0, nil, err
	}
	defer fd.decref()
	for {
		n, sa, err = syscall.Recvfrom(fd.sysfd, p, 0)
		if err == syscall.EAGAIN {
			err = errTimeout
			if fd.rdeadline >= 0 {
				if err = fd.pollServer.WaitRead(fd); err == nil {
					continue
				}
			}
		}
		if err != nil {
			n = 0
		}
		break
	}
	if err != nil && err != io.EOF {
		err = &OpError{"read", fd.net, fd.laddr, err}
	}
	return
}
开发者ID:hfeeki,项目名称:go,代码行数:27,代码来源:fd_unix.go

示例4: recv

func (nlSock *NLSocket) recv() ([]GNLMessage, error) {
	buff := make([]byte, 16384)
	var msgsList []GNLMessage
	for {
		n, _, err := syscall.Recvfrom(nlSock.Sd, buff, 0)
		if err != nil {
			return nil, err
		}
		resp := buff[:n]
		for len(resp) > 0 {
			rmsg, data, err := DeserializeNLMsg(resp)
			if err != nil {
				return nil, err
			}
			if len(msgsList) == 0 && rmsg.Flags&0x2 == 0 {
				return []GNLMessage{rmsg}, nil
			} else if rmsg.Family == DoneMessageType {
				return msgsList, nil
			}
			msgsList = append(msgsList, rmsg)
			resp = data
		}
	}
	return msgsList, nil
}
开发者ID:kobolog,项目名称:gorb,代码行数:25,代码来源:gnl2go.go

示例5: ReadFrom

func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) {
	if fd == nil || fd.sysfile == nil {
		return 0, nil, os.EINVAL
	}
	fd.rio.Lock()
	defer fd.rio.Unlock()
	fd.incref()
	defer fd.decref()
	if fd.rdeadline_delta > 0 {
		fd.rdeadline = pollserver.Now() + fd.rdeadline_delta
	} else {
		fd.rdeadline = 0
	}
	var oserr os.Error
	for {
		var errno int
		n, sa, errno = syscall.Recvfrom(fd.sysfd, p, 0)
		if errno == syscall.EAGAIN && fd.rdeadline >= 0 {
			pollserver.WaitRead(fd)
			continue
		}
		if errno != 0 {
			n = 0
			oserr = os.Errno(errno)
		}
		break
	}
	if oserr != nil {
		err = &OpError{"read", fd.net, fd.laddr, oserr}
	}
	return
}
开发者ID:rapgamer,项目名称:golang-china,代码行数:32,代码来源:fd.go

示例6: ReadFrom

func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
	if err := fd.readLock(); err != nil {
		return 0, nil, err
	}
	defer fd.readUnlock()
	if err := fd.pd.PrepareRead(); err != nil {
		return 0, nil, &OpError{"read", fd.net, fd.laddr, err}
	}
	for {
		n, sa, err = syscall.Recvfrom(fd.sysfd, p, 0)
		if err != nil {
			n = 0
			if err == syscall.EAGAIN {
				if err = fd.pd.WaitRead(); err == nil {
					continue
				}
			}
		}
		err = chkReadErr(n, err, fd)
		break
	}
	if err != nil && err != io.EOF {
		err = &OpError{"read", fd.net, fd.laddr, err}
	}
	return
}
开发者ID:spiralgenetics,项目名称:golang,代码行数:26,代码来源:fd_unix.go

示例7: readFrom

func (fd *netFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
	if err := fd.readLock(); err != nil {
		return 0, nil, err
	}
	defer fd.readUnlock()
	if err := fd.pd.prepareRead(); err != nil {
		return 0, nil, err
	}
	for {
		n, sa, err = syscall.Recvfrom(fd.sysfd, p, 0)
		if err != nil {
			n = 0
			if err == syscall.EAGAIN {
				if err = fd.pd.waitRead(); err == nil {
					continue
				}
			}
		}
		err = fd.eofError(n, err)
		break
	}
	if _, ok := err.(syscall.Errno); ok {
		err = os.NewSyscallError("recvfrom", err)
	}
	return
}
开发者ID:duhaibo0404,项目名称:go-1,代码行数:26,代码来源:fd_unix.go

示例8: Getreply

// Receives messages from Kernel and forwards to channels
func Getreply(s *NetlinkSocket, done <-chan bool, msgchan chan string, errchan chan error) {
	for {
		rb := make([]byte, MAX_AUDIT_MESSAGE_LENGTH)
		nr, _, err := syscall.Recvfrom(s.fd, rb, 0)
		if isDone(msgchan, errchan, done) {
			return
		}
		if err != nil {
			log.Println("Error While Recieving !!")
			errchan <- err
			continue
		}
		if nr < syscall.NLMSG_HDRLEN {
			log.Println("Message Too Short!!")
			errchan <- syscall.EINVAL
			continue
		}

		rb = rb[:nr]
		msgs, err := ParseAuditNetlinkMessage(rb)

		if err != nil {
			log.Println("Not Parsed Successfuly !!")
			errchan <- err
			continue
		}
		for _, m := range msgs {
			//Decide on various message Types
			//Add more message Types
			if m.Header.Type == syscall.NLMSG_DONE {
				log.Println("Done")
			} else if m.Header.Type == syscall.NLMSG_ERROR {
				err := int32(nativeEndian().Uint32(m.Data[0:4]))
				if err == 0 {
					//Acknowledgement from kernel
					log.Println("Ack")
				} else {
					log.Println("NLMSG_ERROR")
				}
			} else if m.Header.Type == AUDIT_GET {
				log.Println("AUDIT_GET")
			} else if m.Header.Type == AUDIT_FIRST_USER_MSG {
				log.Println("AUDIT_FIRST_USER_MSG")
			} else if m.Header.Type == AUDIT_SYSCALL {
				msgchan <- ("type=SYSCALL " + "msg=" + string(m.Data[:]))
			} else if m.Header.Type == AUDIT_CWD {
				msgchan <- ("type=CWD " + "msg=" + string(m.Data[:]))
			} else if m.Header.Type == AUDIT_PATH {
				msgchan <- ("type=PATH " + "msg=" + string(m.Data[:]))
			} else if m.Header.Type == AUDIT_EOE {
				// log.Println("Event Ends ", string(m.Data[:]))
			} else if m.Header.Type == AUDIT_CONFIG_CHANGE {
				msgchan <- ("type=CONFIG_CHANGE " + "msg=" + string(m.Data[:]))
			} else {
				log.Println("Unknown: ", m.Header.Type)
			}
		}
	}

}
开发者ID:hardikj,项目名称:audit-go,代码行数:61,代码来源:libaudit.go

示例9: RecvMessages

func (nl *NetlinkSocket) RecvMessages(sz, sockflags int) ([]NetlinkMessage, error) {
	buf := make([]byte, sz)

	rsz, _, err := syscall.Recvfrom(nl.sfd, buf, sockflags)
	if err != nil {
		return nil, err
	}

	if rsz < syscall.NLMSG_HDRLEN {
		return nil, syscall.EINVAL
	}

	msgList, err := syscall.ParseNetlinkMessage(buf[:rsz])
	if err != nil {
		return nil, err
	}

	ret := []NetlinkMessage{}

	for _, msg := range msgList {
		msg := NetlinkMessage(msg)
		logf("received: %+v\n", msg)
		ret = append(ret, msg)
	}

	return ret, nil
}
开发者ID:apuigsech,项目名称:netlink,代码行数:27,代码来源:netlink.go

示例10: traceOne

func traceOne(addr *syscall.SockaddrInet4, ttl int) *ReturnArgs {
	cli, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
	if err != nil {
		exitWithError(err)
	}
	srv, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
	if err != nil {
		exitWithError(err)
	}

	defer syscall.Close(cli)
	defer syscall.Close(srv)

	// set ttl, stolen from somewhere else...
	// https://github.com/aeden/traceroute/blob/master/traceroute.go#L195
	if err := syscall.SetsockoptInt(cli, syscall.SOL_IP, syscall.IP_TTL, ttl); err != nil {
		exitWithError(err)
	}

	// set timeout, stolen from somewhere else...
	// https://github.com/aeden/traceroute/blob/master/traceroute.go#L197
	tv := syscall.NsecToTimeval(1e6 * TIMEOUT)
	if err := syscall.SetsockoptTimeval(srv, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv); err != nil {
		exitWithError(err)
	}
	if err := syscall.Bind(srv, toAddr(HOST, RECV_PORT)); err != nil {
		exitWithError(err)
	}

	rr := &ReturnArgs{}
	start := time.Now()
	if err := syscall.Sendto(cli, makeICMP(), 0, addr); err != nil {
		return rr
	}

	buf := make([]byte, 512)
	_, from, err := syscall.Recvfrom(srv, buf, 0)
	if err != nil {
		return rr
	}

	rr.elapsed = float64(time.Since(start).Nanoseconds()) / 1e6
	t, c := parseICMP(buf)
	if t == 3 && c == 3 { // Destination port unreachable, type==3 && code==3
		rr.done = true
	} else if t != 11 { // Time Exceeded, type==11 && code in (0,1)
		return rr
	}
	rr.ok = true
	rr.ip = toStr(from)
	addrs, err := net.LookupAddr(rr.ip)
	if err != nil {
		rr.addr = rr.ip
	} else {
		rr.addr = addrs[0]
	}
	return rr
}
开发者ID:damnever,项目名称:traceroute,代码行数:58,代码来源:traceroute.go

示例11: Traceroute

// Traceroute executes traceroute to given destination, using options from TracerouteOptions
// and sending updates to chan c
//
// Outbound packets are UDP packets and inbound packets are ICMP.
//
// Returns an error or nil if no error occurred
func Traceroute(dest *net.IPAddr, options *TracerouteOptions, c chan TraceUpdate) (err error) {
	var destAddr [4]byte
	copy(destAddr[:], dest.IP.To4())
	socketAddr, err := getSocketAddr()
	if err != nil {
		return
	}

	timeoutMs := (int64)(options.TimeoutMs)
	tv := syscall.NsecToTimeval(1000 * 1000 * timeoutMs)

	ttl := 1
	for {
		// Set up receiving socket
		recvSocket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
		if err != nil {
			log.Fatal("Cannot setup receive socket, please run as root or with CAP_NET_RAW permissions")
			return err
		}
		// Set up sending socket
		sendSocket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
		if err != nil {
			log.Fatal("Cannot setup sending socket")
			return err
		}

		start := time.Now()
		syscall.SetsockoptInt(sendSocket, 0x0, syscall.IP_TTL, ttl)
		syscall.SetsockoptTimeval(recvSocket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv)
		syscall.Bind(recvSocket, &syscall.SockaddrInet4{Port: options.Port, Addr: socketAddr})
		syscall.Sendto(sendSocket, []byte{0x0}, 0, &syscall.SockaddrInet4{Port: options.Port, Addr: destAddr})

		var p = make([]byte, options.PacketSize)
		n, from, err := syscall.Recvfrom(recvSocket, p, 0)
		elapsed := time.Since(start)
		if err == nil {
			currAddr := from.(*syscall.SockaddrInet4).Addr
			hop := TraceUpdate{Success: true, Address: currAddr, N: n, ElapsedTime: elapsed, TTL: ttl}
			currHost, err := net.LookupAddr(hop.addressString())
			if err == nil {
				hop.Host = currHost[0]
			}
			// Send update
			c <- hop
			ttl += 1
			// We reached the destination
			if ttl > options.MaxTTL || currAddr == destAddr {
				ttl = 1
			}
		} else {
			c <- TraceUpdate{Success: false, TTL: ttl}
			ttl += 1
		}
		syscall.Close(recvSocket)
		syscall.Close(sendSocket)
	}
}
开发者ID:mag-,项目名称:gtr,代码行数:63,代码来源:trace.go

示例12: receiveICMP

func receiveICMP(result chan icmpEvent) {

	// Set up the socket to receive inbound packets
	sock, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
	if err != nil {
		result <- makeICMPErrorEvent(&icmpEvent{}, fmt.Errorf("%v. Did you forget to run as root?", err))
		return
	}

	err = syscall.Bind(sock, &syscall.SockaddrInet4{})
	if err != nil {
		result <- makeICMPErrorEvent(&icmpEvent{}, err)
		return
	}

	var pkt = make([]byte, 1024)
	for {
		event := icmpEvent{}
		_, from, err := syscall.Recvfrom(sock, pkt, 0)
		if err != nil {
			result <- makeICMPErrorEvent(&event, err)
			return
		}
		reader := bytes.NewReader(pkt)
		var ip IPHeader
		var icmp ICMPHeader
		var tcp TCPHeader

		err = binary.Read(reader, binary.BigEndian, &ip)
		if ip.Protocol != syscall.IPPROTO_ICMP {
			break
		}

		ipheaderlen := (ip.VerHdrLen & 0xf) * 4
		reader = bytes.NewReader(pkt[ipheaderlen:])

		err = binary.Read(reader, binary.BigEndian, &icmp)
		if icmp.Type != 11 || icmp.Code != 0 {
			break
		}

		err = binary.Read(reader, binary.BigEndian, &ip)

		if ip.Protocol != syscall.IPPROTO_TCP {
			break
		}

		err = binary.Read(reader, binary.BigEndian, &tcp)

		event.localAddr.IP = append(event.localAddr.IP, ip.SourceIP[:]...)
		event.localPort = int(tcp.SrcPort)

		// fill in the remote endpoint deatils on the event struct
		event.remoteAddr, _, _ = ToIPAddrAndPort(from)
		result <- makeICMPEvent(&event, icmpTTLExpired)
	}
}
开发者ID:simulatedsimian,项目名称:tracetcp-go,代码行数:57,代码来源:icmp.go

示例13: Getreply

// Receives messages from Kernel and forwards to channels
func Getreply(s *NetlinkSocket, done <-chan bool, msgchan chan string, errchan chan error) {
	for {
		rb := make([]byte, MAX_AUDIT_MESSAGE_LENGTH)
		nr, _, err := syscall.Recvfrom(s.fd, rb, 0)
		if isDone(msgchan, errchan, done) {
			return
		}
		if err != nil {
			log.Println("Error While Recieving !!")
			errchan <- err
			continue
		}
		if nr < syscall.NLMSG_HDRLEN {
			log.Println("Message Too Short!!")
			errchan <- syscall.EINVAL
			continue
		}

		rb = rb[:nr]
		msgs, err := ParseAuditNetlinkMessage(rb)

		if err != nil {
			log.Println("Not Parsed Successfuly !!")
			errchan <- err
			continue
		}

		for _, m := range msgs {
			//Decide on various message Types
			if m.Header.Type == syscall.NLMSG_DONE {
				log.Println("Done")
			} else if m.Header.Type == syscall.NLMSG_ERROR {
				err := int32(nativeEndian().Uint32(m.Data[0:4]))
				if err == 0 {
					//Acknowledgement from kernel
					log.Println("Ack")
				} else {
					log.Println("NLMSG_ERROR")
				}
			} else if m.Header.Type == uint16(AUDIT_EOE) {
				// log.Println("Event Ends ", string(m.Data[:]))
			} else if m.Header.Type == uint16(AUDIT_GET) {
				log.Println("AUDIT_GET")
			} else if m.Header.Type == uint16(AUDIT_FIRST_USER_MSG) {
				log.Println("AUDIT_FIRST_USER_MSG")
			} else {
				Type := auditConstant(m.Header.Type)
				if Type.String() == "auditConstant("+strconv.Itoa(int(m.Header.Type))+")" {
					log.Println("Unknown: ", m.Header.Type)
				} else {
					msgchan <- ("type=" + Type.String()[6:] + " msg=" + string(m.Data[:]))
				}
			}
		}
	}

}
开发者ID:hardikj,项目名称:libaudit-go,代码行数:58,代码来源:libaudit.go

示例14: receive

func receive() (arpDatagram, time.Time, error) {
	buffer := make([]byte, 128)
	n, _, err := syscall.Recvfrom(sock, buffer, 0)
	if err != nil {
		return arpDatagram{}, time.Now(), err
	}
	// skip 14 bytes ethernet header
	return parseArpDatagram(buffer[14:n]), time.Now(), nil
}
开发者ID:j-keck,项目名称:lsleases,代码行数:9,代码来源:arping_linux.go

示例15: RecvMessagesRaw

func (nl *NetlinkSocket) RecvMessagesRaw(sz, sockflags int) ([]byte, error) {
	buf := make([]byte, sz)

	rsz, _, err := syscall.Recvfrom(nl.sfd, buf, sockflags)
	if err != nil {
		return nil, err
	}

	return buf[:rsz], nil
}
开发者ID:apuigsech,项目名称:netlink,代码行数:10,代码来源:netlink.go


注:本文中的syscall.Recvfrom函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。