public void SendCyclicData(PhysicalAddress destination, UInt16 frameID, UInt16 cycleCounter, byte[] userData)
        {
            Trace.WriteLine("Sending cyclic data", null);

            MemoryStream mem = new MemoryStream();

            //ethernet
            Ethernet.Encode(mem, destination, adapter.MacAddress, (Ethernet.Type) 0x8892);

            //Profinet Real Time
            RT.EncodeFrameId(mem, (RT.FrameIds)frameID);

            //user data
            if (userData == null)
            {
                userData = new byte[40];
            }
            if (userData.Length < 40)
            {
                Array.Resize <byte>(ref userData, 40);
            }
            mem.Write(userData, 0, userData.Length);

            //RT footer
            RT.EncodeRTCStatus(mem, cycleCounter, RT.DataStatus.DataItemValid |
                               RT.DataStatus.State_Primary |
                               RT.DataStatus.ProviderState_Run |
                               RT.DataStatus.StationProblemIndicator_Normal,
                               RT.TransferStatus.OK);

            //Send
            Send(mem);
        }
예제 #2
0
        public CounterSample(byte[] buffer) : base(buffer)
        {
            Records = new CounterRecord[buffer.ToUInt(16, 4)];
            uint recordStartIndex = 20;

            for (uint i = 0; i < Records.Length; i++)
            {
                CounterRecord record       = new CounterRecord(buffer.AsSpan((int)recordStartIndex, (int)Record.HeaderLengthBytes).ToArray());
                int           recordLength = (int)(record.Length + Record.HeaderLengthBytes);
                if (record.Type == RecordType.GenericInterface)
                {
                    record = new Records.Generic(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                else if (record.Type == RecordType.EthernetInterface)
                {
                    record = new Ethernet(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                else if (record.Type == RecordType.VLAN)
                {
                    record = new VLAN(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                else if (record.Type == RecordType.ProcessorInformation)
                {
                    record = new ProcessorInfo(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                recordStartIndex += (uint)recordLength;
                Records[i]        = record;
            }
        }
예제 #3
0
        public TcpConnection(Ethernet ethHeader,
                             IPv4 ipHeader,
                             Network.Header.Tcp tcpHeader,
                             TTransmitter packetTransmitter,
                             PipeScheduler readScheduler,
                             PipeScheduler writeScheduler,
                             MemoryPool <byte> memoryPool,
                             IConnectionDispatcher connectionDispatcher)
        {
            _packetTransmitter      = packetTransmitter;
            _connectionDispatcher   = connectionDispatcher;
            _remoteAddress          = ipHeader.SourceAddress;
            _localAddress           = ipHeader.DestinationAddress;
            _outboundEthernetHeader = new Ethernet()
            {
                Destination = ethHeader.Source, Ethertype = EtherType.IPv4, Source = ethHeader.Destination
            };
            var pseudo = new TcpV4PseudoHeader()
            {
                Destination = _remoteAddress, Source = _localAddress, ProtocolNumber = Internet.Ip.ProtocolNumber.Tcp, Reserved = 0
            };

            _pseudoPartialSum = Checksum.PartialCalculate(ref Unsafe.As <TcpV4PseudoHeader, byte>(ref pseudo), Unsafe.SizeOf <TcpV4PseudoHeader>());

            LocalAddress  = new System.Net.IPAddress(_localAddress.Address);
            RemoteAddress = new System.Net.IPAddress(_remoteAddress.Address);
            RemotePort    = tcpHeader.SourcePort;
            LocalPort     = tcpHeader.DestinationPort;

            OutputReaderScheduler = readScheduler ?? throw new ArgumentNullException(nameof(readScheduler));
            InputWriterScheduler  = writeScheduler ?? throw new ArgumentNullException(nameof(writeScheduler));
            MemoryPool            = memoryPool ?? throw new ArgumentNullException(nameof(memoryPool));

            ConnectionClosed = _closedToken.Token;
        }
    static int EntryPoint()
    {
        // Create and start the thread for the CAM controller
        CAM_controller cam_controller     = new CAM_controller();
        Thread         CAM_lookup_n_learn = new Thread(new ThreadStart(cam_controller.CAM_lookup_n_learn));

        CAM_lookup_n_learn.Start();

        // Create and start the thread for the ethernet parser
        Ethernet eth_controller = new Ethernet();
        Thread   eth_ctrl       = new Thread(new ThreadStart(eth_controller.eth_parser));

        eth_ctrl.Start();

        // Create and start the thread for the FIFO controller
        FIFO_controller fifo_controller = new FIFO_controller();
//		Thread FIFO_receive = new Thread(new ThreadStart(fifo_controller.FIFO_receive));
//		FIFO_receive.Start();
        Thread FIFO_send = new Thread(new ThreadStart(fifo_controller.FIFO_send));

        FIFO_send.Start();
        while (true)
        {
            Kiwi.Pause();
        }
        ;
        return(0);
    }
예제 #5
0
파일: Router.cs 프로젝트: shirriff/IFS
        public void RegisterRAWInterface(LivePacketDevice iface)
        {
            Ethernet enet = new Ethernet(iface);

            _pupPacketInterface = enet;
            _rawPacketInterface = enet;
            _pupPacketInterface.RegisterRouterCallback(RouteIncomingLocalPacket);
        }
예제 #6
0
        //htonl(0x7F000001); // 127.0.0.1
        public void Append(IPEndPoint source, IPEndPoint destination, ProtocolType protocol, byte[] payload, DateTime?timestamp = null)
        {
            PcapItemHeader packetHeader;
            Ethernet       packetEthernet;
            IPv4           packetIP;
            UDP            packetUDP;

            byte[] sourceBytes, destinationBytes;

            byte[] payloadItemHeader, payloadEthernet, payloadIP, payloadUDP, payloadData;
            int    index;

            /* UDP */
            packetUDP  = new UDP((UInt16)source.Port, (UInt16)destination.Port, (UInt16)payload.Length);
            payloadUDP = packetUDP.GetBytes();

            /* ipv4 */
            packetIP  = new IPv4(source.Address, destination.Address, protocol, (UInt16)(payloadUDP.Length + payload.Length));
            payloadIP = packetIP.GetBytes();

            /* ethernet */
            sourceBytes      = source.Address.GetAddressBytes();
            destinationBytes = destination.Address.GetAddressBytes();
            packetEthernet   = new Ethernet(new byte[3] {
                sourceBytes[1], sourceBytes[2], sourceBytes[3]
            }, new byte[3] {
                destinationBytes[1], destinationBytes[2], destinationBytes[3]
            });
            payloadEthernet = packetEthernet.GetBytes();

            /* pcap packet header */
            if (timestamp == null)
            {
                timestamp = DateTime.UtcNow;
            }
            packetHeader      = new PcapItemHeader((DateTime)timestamp, (UInt32)(payloadEthernet.Length + payloadIP.Length + payloadUDP.Length + payload.Length));
            payloadItemHeader = packetHeader.GetBytes();

            payloadData = new byte[payloadItemHeader.Length + payloadEthernet.Length + payloadIP.Length + payloadUDP.Length + payload.Length];

            index = 0;
            payloadItemHeader.CopyTo(payloadData, index);
            index += payloadItemHeader.Length;

            payloadEthernet.CopyTo(payloadData, index);
            index += payloadEthernet.Length;

            payloadIP.CopyTo(payloadData, index);
            index += payloadIP.Length;

            payloadUDP.CopyTo(payloadData, index);
            index += payloadUDP.Length;

            payload.CopyTo(payloadData, index);
            index += payload.Length;

            content.Write(payloadData, 0, payloadData.Length);
        }
예제 #7
0
        public void Send(Ethernet frame, bool sendAsync)
        {
            if (!frame.Src.IsSet())
            {
                frame.Src = Option <byte[]> .Of(MACAddress);
            }

            Send(frame.ToEthernetFrame(), sendAsync);
        }
예제 #8
0
 protected override void ControlsToData()
 {
     if (_bus == null)
     {
         _bus = new Ethernet();
     }
     base.ControlsToData();
     ((Ethernet)_bus).supportsDHCP = chkSupportsDHCP.Checked;
 }
예제 #9
0
 private void genBackTools() {
     Ethernet eth = new Ethernet();
     UJack ujack = new UJack();
     UnPort up = new UnPort();
     backTools btsArray = new backTools();
     btsArray.Add(eth);
     btsArray.Add(ujack);
     btsArray.Add(up);
     this.back_tools.ItemsSource = btsArray;
 }
예제 #10
0
 internal Network(CiscoTelePresenceCodec codec, int indexer)
     : base(codec, indexer)
 {
     _cdp      = new Cdp(this, "CDP");
     _dns      = new Dns(this, "DNS");
     _ethernet = new Ethernet(this, "Ethernet");
     _ipv4     = new Ipv4(this, "IPV4");
     _ipv6     = new Ipv6(this, "IPV6");
     _vlan     = new Vlan(this, "VLAN");
 }
예제 #11
0
        public void Load()
        {
            mac = new MacSetting();
            mac.Change("12-12-12-12-12-12");
            interfaces = new List <NetInterface>();
            NetInterface eth1    = new Ethernet(0, "12-12-12-12-12-12");
            NetInterface wifi    = new Wifi(1, "12-12-12-12-12-12");
            NetInterface console = new lab3.Console(2, "12-12-12-12-12-12");

            interfaces.Add(eth1);
            interfaces.Add(wifi);
            interfaces.Add(console);
        }
예제 #12
0
 public void RunLANTest(bool single, bool stop)
 {
     if (single)
     {
         Ethernet lan = new Ethernet(F1, COMPort);
         lan.Start_Test();
     }
     else
     {
         if (F1.getCheckStatus((COMPort == 1) ? (F1.LANCheck) : (F1.LANCheck2)) && !stop)
         {
             Ethernet lan = new Ethernet(F1, COMPort);
             lan.Start_Test();
         }
     }
 }
예제 #13
0
파일: Nic.cs 프로젝트: Paul1nh0/Singularity
        // Get the received packets from the adapter
        void DeMuxReceivedPackets()
        {
            //Grab the latest set of packets
            RxExchange();

            PacketFifo newPackets = this.rxFifo.Acquire();

            try {
                int count = newPackets.Count;
                for (int i = 0; i < count; i++)
                {
                    Packet packet = newPackets.Pop();

                    // If packet from device has an error
                    // recycle it right away.
                    FromDeviceFlags fromFlags = packet.FromDeviceFlags;
                    if ((fromFlags & FromDeviceFlags.ReceiveError) != 0)
                    {
                        DebugStub.Print("Packet had error???\n");
                        newPackets.Push(packet);
                        continue;
                    }
                    Bytes data = packet.ReleaseFragment(0);
                    Ethernet.ProcessIncomingPacket(data, this);
#if  false
                    if (filterAdapter == null ||
                        filterAdapter.ProcessIncomingPacket(data))
                    {
                        Ethernet.ProcessIncomingPacket(data, this);
                    }
                    else
                    {
                        //delete data;
                    }
#endif
                    //XXX Totally inefficient first try immediately replaces
                    //the lost data.
                    Bytes nxtPacket = new Bytes(new byte[this.mtu]);
                    packet.SetFragment(0, nxtPacket);
                    newPackets.Push(packet);
                }
            }
            finally {
                this.rxFifo.Release(newPackets);
            }
        }
예제 #14
0
        public Maquina(string nome, Endereco ipAddress, EnderecoMAC enderecoMac, Endereco mascara)
        {
            this.nome        = nome;
            endereco         = ipAddress;
            this.enderecoMac = enderecoMac;
            this.mascara     = mascara;


            /** Criação das camadas */
            ethernet   = new Ethernet(enderecoMac);
            ip         = new IP(endereco, mascara);
            udp        = new UDP();
            aplicacoes = new List <Aplicacao>();

            /** Cliente DNS */
            clienteDNS = new ClienteDNS(1024, this);
            Adicionar(1024, clienteDNS);
        }
예제 #15
0
        private static void InitNetwork()
        {
            if (!Ethernet.IsEnabled)
            {
                Ethernet.Enable();
            }

            Thread checkNetwork = new Thread(new ThreadStart(() =>
            {
                bool wasNetworkAvailable = false;
                while (true)
                {
                    if (Ethernet.IsCableConnected)
                    {
                        if (!wasNetworkAvailable)
                        {
                            wasNetworkAvailable = true;
                            SetNetwokSettings();
                            if (OnNetworkConnected != null)
                            {
                                OnNetworkConnected();
                            }
                        }
                    }
                    else
                    {
                        if (wasNetworkAvailable)
                        {
                            wasNetworkAvailable = false;
                            if (OnNetworkDisconnected != null)
                            {
                                OnNetworkDisconnected();
                            }
                        }
                    }
                    Thread.Sleep(3000);
                }
            }));

            checkNetwork.Start();
        }
        public void SendIdentifyResponse(PhysicalAddress destination, uint xid, Dictionary <DCP.BlockOptions, object> blocks)
        {
            Trace.WriteLine("Sending identify response", null);

            MemoryStream mem = new MemoryStream();

            //ethernet
            Ethernet.Encode(mem, destination, adapter.MacAddress, Ethernet.Type.VLanTaggedFrame);

            //VLAN
            VLAN.Encode(mem, VLAN.Priorities.Priority0, VLAN.Type.PN);

            //Profinet Real Time
            RT.EncodeFrameId(mem, RT.FrameIds.DCP_Identify_ResPDU);

            //Profinet DCP
            DCP.EncodeIdentifyResponse(mem, xid, blocks);

            //Send
            Send(mem);
        }
        public void SendSetResponse(PhysicalAddress destination, uint xid, DCP.BlockOptions option, DCP.BlockErrors status)
        {
            Trace.WriteLine("Sending Set " + option.ToString() + " response", null);

            MemoryStream mem = new MemoryStream();

            //ethernet
            Ethernet.Encode(mem, destination, adapter.MacAddress, Ethernet.Type.VLanTaggedFrame);

            //VLAN
            VLAN.Encode(mem, VLAN.Priorities.Priority0, VLAN.Type.PN);

            //Profinet Real Time
            RT.EncodeFrameId(mem, RT.FrameIds.DCP_Get_Set_PDU);

            //Profinet DCP
            DCP.EncodeSetResponse(mem, xid, option, status);

            //Send
            Send(mem);
        }
예제 #18
0
        public unsafe T TryConsume <T>(T buffer) where T : IMemoryOwner <byte>
        {
            var input = buffer.Memory.Span;

            WriteLine($"---> Received {input.Length} byte packet");
            bool result;

            if (Ethernet.TryConsume(input, out var etherIn, out var data))
            {
                WriteLine($"{etherIn.ToString()}");

                if (etherIn.Ethertype == EtherType.IPv4)
                {
                    result = TryConsumeIPv4(in etherIn, data);
                }
                else
                {
                    WriteLine($"{ etherIn.Ethertype.ToString().PadRight(11)} ---> {BitConverter.ToString(data.ToArray()).MaxLength(60)}");
                    // Pass on to host
                    result = false;
                }
            }
        public IAsyncResult BeginGetRequest(PhysicalAddress destination, DCP.BlockOptions option)
        {
            Trace.WriteLine("Sending Get " + option.ToString() + " request", null);

            MemoryStream mem = new MemoryStream();

            //ethernet
            Ethernet.Encode(mem, destination, adapter.MacAddress, Ethernet.Type.VLanTaggedFrame);

            //VLAN
            VLAN.Encode(mem, VLAN.Priorities.Priority0, VLAN.Type.PN);

            //Profinet Real Time
            RT.EncodeFrameId(mem, RT.FrameIds.DCP_Get_Set_PDU);

            //Profinet DCP
            UInt16 xid = ++lastXid;

            DCP.EncodeGetRequest(mem, xid, option);
            //start Async
            return(new ProfinetAsyncDcpResult(this, mem, xid));
        }
        public void SendIdentifyBroadcast()
        {
            Trace.WriteLine("Sending identify broadcast", null);

            MemoryStream mem = new MemoryStream();

            //ethernet
            PhysicalAddress ethernetDestinationHwAddress = PhysicalAddress.Parse(RT.MulticastMACAdd_Identify_Address);

            Ethernet.Encode(mem, ethernetDestinationHwAddress, adapter.MacAddress, Ethernet.Type.VLanTaggedFrame);

            //VLAN
            VLAN.Encode(mem, VLAN.Priorities.Priority0, VLAN.Type.PN);

            //Profinet Real Time
            RT.EncodeFrameId(mem, RT.FrameIds.DCP_Identify_ReqPDU);

            //Profinet DCP
            DCP.EncodeIdentifyRequest(mem, ++lastXid);

            //Send
            Send(mem);
        }
예제 #21
0
파일: WinTunPort.cs 프로젝트: InJoins/Magma
 private void TestIpV4(Memory <byte> input)
 {
     var eth  = Ethernet.TryConsume(input.Span, out var ethernet, out var data);
     var ipv4 = IPv4.TryConsume(input.Span, out var ip, out data);
 }
예제 #22
0
 public EthernetFrame(EthernetPort dst, EthernetPort src, Option <ushort> vlan, Layer3Packet layer3Packet)
 {
     _apiEthernet = Generators.Ethernet(dst, src) | Generators.Dot1Q(vlan);
     _apiEthernet = layer3Packet.Merge(_apiEthernet);
 }
예제 #23
0
 public EthernetFrame(EthernetPort dst, EthernetPort src, Layer3Packet layer3Packet)
 {
     _apiEthernet = Generators.Ethernet(dst, src);
     _apiEthernet = layer3Packet.Merge(_apiEthernet);
 }
예제 #24
0
 public Ethernet Merge(Ethernet ethernet)
 {
     return(ethernet | RawPacket(_bytes));
 }
예제 #25
0
 protected override void OnAppearing()
 {
     base.OnAppearing();
     Ethernet.CheckConnection();
 }
        public override void Run()
        {
            // Login
            VapiAuthHelper           = new VapiAuthenticationHelper();
            SessionStubConfiguration =
                VapiAuthHelper.LoginByUsernameAndPassword(
                    Server, UserName, Password);

            this.diskService = VapiAuthHelper.StubFactory.CreateStub <Disk>(
                SessionStubConfiguration);
            this.ethernetService =
                VapiAuthHelper.StubFactory.CreateStub <Ethernet>(
                    SessionStubConfiguration);
            this.bootDeviceService =
                VapiAuthHelper.StubFactory.CreateStub <Device>(
                    SessionStubConfiguration);

            Console.WriteLine("\n\n#### Setup: Get the virtual machine id");
            this.vmId = VmHelper.GetVm(VapiAuthHelper.StubFactory,
                                       SessionStubConfiguration, VmName);
            Console.WriteLine("\nUsing VM: " + VmName + " (vmId="
                              + this.vmId + " ) for boot device configuration sample");

            Console.WriteLine("\nValidate whether the VM has the required "
                              + "minimum number of devices");
            VM vmService = VapiAuthHelper.StubFactory.CreateStub <VM>(
                SessionStubConfiguration);

            VMTypes.Info vmInfo = vmService.Get(this.vmId);
            if (vmInfo.GetCdroms().Count < 1 || vmInfo.GetFloppies().Count < 1 ||
                vmInfo.GetDisks().Count < 1 || vmInfo.GetNics().Count < 1)
            {
                throw new Exception("\n Selected VM does not have the required "
                                    + "minimum number of devices: i.e. 1 Ethernet adapter, "
                                    + "1 CD-ROM, 1 Floppy drive, 3 disks");
            }

            Console.WriteLine("\n\n#### Example: Print the current boot device"
                              + " configuration");
            List <DeviceTypes.Entry> bootDeviceEntries =
                this.bootDeviceService.Get(this.vmId);

            bootDeviceEntries.ForEach(i => Console.WriteLine(i));

            // Save the current boot info to revert it during cleanup
            this.orginalBootDeviceEntries = bootDeviceEntries;

            Console.WriteLine("\n\n#### Example: Set boot order to be Floppy, "
                              + "Disk1, Disk2, Disk3, Ethernet NIC, CD-ROM");

            // Get the device identifiers for disks
            List <DiskTypes.Summary> diskSummaries =
                this.diskService.List(this.vmId);

            Console.WriteLine("\nList of disks attached to the VM: \n");
            diskSummaries.ForEach(i => Console.WriteLine(i));
            List <String> diskIds = new List <String>();

            foreach (DiskTypes.Summary diskSummary in diskSummaries)
            {
                diskIds.Add(diskSummary.GetDisk());
            }

            // Get device identifiers for Ethernet NICs
            List <EthernetTypes.Summary> ethernetSummaries =
                this.ethernetService.List(this.vmId);

            Console.WriteLine("\nList of Ethernet NICs attached to the VM:\n");
            ethernetSummaries.ForEach(i => Console.WriteLine(i));
            List <String> ethernetIds = new List <String>();

            foreach (EthernetTypes.Summary ethernetSummary in ethernetSummaries)
            {
                ethernetIds.Add(ethernetSummary.GetNic());
            }

            List <DeviceTypes.Entry> devices = new List <DeviceTypes.Entry>(4);

            devices.Add(new DeviceTypes.Entry());
            devices[0].SetType(DeviceTypes.Type.FLOPPY);

            devices.Add(new DeviceTypes.Entry());
            devices[1].SetDisks(diskIds);
            devices[1].SetType(DeviceTypes.Type.DISK);

            devices.Add(new DeviceTypes.Entry());
            devices[2].SetNic(ethernetIds[0]);
            devices[2].SetType(DeviceTypes.Type.ETHERNET);

            devices.Add(new DeviceTypes.Entry());
            devices[3].SetType(DeviceTypes.Type.CDROM);

            this.bootDeviceService.Set(this.vmId, devices);
            bootDeviceEntries = this.bootDeviceService.Get(this.vmId);
            Console.WriteLine("\nNew boot device configuration");
            bootDeviceEntries.ForEach(i => Console.WriteLine(i));
        }
예제 #27
0
 public void SendSync(Ethernet frame)
 {
     Send(frame, false);
 }
예제 #28
0
 public TcpConnection(Ethernet ethHeader, IPv4 ipHeader, Network.Header.Tcp tcpHeader, TTransmitter packetTransmitter, IConnectionDispatcher connectionDispatcher)
     : this(ethHeader, ipHeader, tcpHeader, packetTransmitter, PipeScheduler.ThreadPool, PipeScheduler.ThreadPool, MemoryPool <byte> .Shared, connectionDispatcher)
 {
 }
예제 #29
0
        //htonl(0x7F000001); // 127.0.0.1
        public void Append(IPEndPoint source, IPEndPoint destination, ProtocolType protocol, byte[] payload, DateTime?timestamp = null)
        {
            PcapItemHeader packetHeader;
            Ethernet       packetEthernet;
            IPv4           packetIP;

            byte[] sourceBytes, destinationBytes;

            byte[] payloadItemHeader, payloadEthernet, payloadIP, payloadTransport, payloadData;
            int    index;

            switch (protocol)
            {
            case ProtocolType.Udp:
                UDP packetUDP;
                packetUDP        = new UDP((UInt16)source.Port, (UInt16)destination.Port, (UInt16)payload.Length);
                payloadTransport = packetUDP.GetBytes();
                break;

            case ProtocolType.Tcp:
                TCP    packetTCP;
                UInt16 connection1, connection2;

                UInt64 seqAck;
                UInt32 seq, ack;

                connection1 = tcpConnectionId(source, destination);
                connection2 = tcpConnectionId(destination, source);
                if (tcpWindows.ContainsKey(connection1))
                {
                    seqAck = tcpWindows[connection1];
                    seq    = (UInt32)(seqAck >> 32);
                    ack    = (UInt32)seqAck;
                }
                else
                {
                    seq    = 1;
                    ack    = 1;
                    seqAck = ((UInt64)seq << 32) | ack;
                    tcpWindows.Add(connection1, seqAck);
                }

                packetTCP = new TCP((UInt16)source.Port, (UInt16)destination.Port, seq, ack);

                seq   += (UInt32)payload.Length;
                seqAck = ((UInt64)seq << 32) | ack;
                tcpWindows[connection1] = seqAck;

                if (tcpWindows.ContainsKey(connection2))
                {
                    seqAck = tcpWindows[connection2];
                    seq    = (UInt32)(seqAck >> 32);
                    ack    = (UInt32)payload.Length;

                    seqAck = ((UInt64)seq << 32) | ack;
                    tcpWindows[connection2] = seqAck;
                }
                else
                {
                    seq = 1;
                    ack = (UInt32)payload.Length;

                    seqAck = ((UInt64)seq << 32) | ack;
                    tcpWindows.Add(connection2, seqAck);
                }

                payloadTransport = packetTCP.GetBytes();
                break;

            case ProtocolType.IP:
                payloadTransport = new byte[] { };
                break;

            default:
                throw new System.ArgumentException("This protocol is not supported", "protocol");
            }


            /* ipv4 */
            packetIP  = new IPv4(source.Address, destination.Address, protocol, (UInt16)(payloadTransport.Length + payload.Length));
            payloadIP = packetIP.GetBytes();

            /* ethernet */
            sourceBytes      = source.Address.GetAddressBytes();
            destinationBytes = destination.Address.GetAddressBytes();
            packetEthernet   = new Ethernet(new byte[3] {
                sourceBytes[1], sourceBytes[2], sourceBytes[3]
            }, new byte[3] {
                destinationBytes[1], destinationBytes[2], destinationBytes[3]
            });
            payloadEthernet = packetEthernet.GetBytes();

            /* pcap packet header */
            if (timestamp == null)
            {
                timestamp = DateTime.UtcNow;
            }
            packetHeader      = new PcapItemHeader((DateTime)timestamp, (UInt32)(payloadEthernet.Length + payloadIP.Length + payloadTransport.Length + payload.Length));
            payloadItemHeader = packetHeader.GetBytes();

            payloadData = new byte[payloadItemHeader.Length + payloadEthernet.Length + payloadIP.Length + payloadTransport.Length + payload.Length];

            index = 0;
            payloadItemHeader.CopyTo(payloadData, index);
            index += payloadItemHeader.Length;

            payloadEthernet.CopyTo(payloadData, index);
            index += payloadEthernet.Length;

            payloadIP.CopyTo(payloadData, index);
            index += payloadIP.Length;

            payloadTransport.CopyTo(payloadData, index);
            index += payloadTransport.Length;

            payload.CopyTo(payloadData, index);
            index += payload.Length;

            if (payloadData.Length != packetHeader.length + 16)
            {
                throw new Exception("Error of PCap. Possible bug");
            }

            content.Write(payloadData, 0, payloadData.Length);
        }
예제 #30
0
        static void Main(string[] args)
        {
            PcapHeader     fileHeader;
            PcapItemHeader packetHeader;
            Ethernet       packetEthernet;
            IPv4           packetIP;
            UDP            packetUDP;
            UInt16         destPort;

            byte[]   payloadFileHeader, payloadItemHeader, payloadEthernet, payloadIP, payloadUDP, payloadData;
            DateTime captureTime;

            byte[] payload;
            int    index;

            string source, dest;

            if (args.Length < 2)
            {
                usage();
                return;
            }

            if (args.Length > 2)
            {
                if (!UInt16.TryParse(args[2], out destPort))
                {
                    Console.WriteLine(String.Format("Error: The value {0} is not a valid port number!", args[2]));
                    usage();
                    return;
                }
            }
            else
            {
                destPort = 0;
            }

            source = args[0];
            dest   = args[1];



            if (!File.Exists(source))
            {
                Console.WriteLine(String.Format("Error: File {0} does not exists!", source));
            }
            if (File.Exists(dest))
            {
                Console.WriteLine(String.Format("Error: File {0} already exists! Please delete it first.", dest));
            }

            try
            {
                /* load payload */
                payloadData = File.ReadAllBytes(source);
                captureTime = File.GetLastWriteTimeUtc(source);

                /* UDP */
                packetUDP  = new UDP(destPort, (UInt16)payloadData.Length);
                payloadUDP = packetUDP.GetBytes();

                /* ipv4 */
                packetIP  = new IPv4((UInt16)(payloadUDP.Length + payloadData.Length));
                payloadIP = packetIP.GetBytes();

                /* ethernet */
                packetEthernet  = new Ethernet(1);
                payloadEthernet = packetEthernet.GetBytes();

                /* pcap packet header */
                packetHeader      = new PcapItemHeader(captureTime, (UInt32)(payloadEthernet.Length + payloadIP.Length + payloadUDP.Length + payloadData.Length));
                payloadItemHeader = packetHeader.GetBytes();

                /* pcap file header */
                fileHeader        = new PcapHeader(1);
                payloadFileHeader = fileHeader.GetBytes();

                payload = new byte[payloadFileHeader.Length + payloadItemHeader.Length + payloadEthernet.Length + payloadIP.Length + payloadUDP.Length + payloadData.Length];

                index = 0;
                payloadFileHeader.CopyTo(payload, index);
                index += payloadFileHeader.Length;

                payloadItemHeader.CopyTo(payload, index);
                index += payloadItemHeader.Length;

                payloadEthernet.CopyTo(payload, index);
                index += payloadEthernet.Length;

                payloadIP.CopyTo(payload, index);
                index += payloadIP.Length;

                payloadUDP.CopyTo(payload, index);
                index += payloadUDP.Length;

                payloadData.CopyTo(payload, index);
                index += payloadData.Length;

                File.WriteAllBytes(dest, payload);
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Error: Unable to convert '{0}' to '{1}'!", source, dest));
                Console.WriteLine(e.ToString());
                return;
            }

            Console.WriteLine(String.Format("'{0}' -> '{1}'", source, dest));
        }
예제 #31
0
 public void SendAsync(Ethernet frame)
 {
     Send(frame, true);
 }