public Task <SaveResult> SendSignalRequest(ICaptureDevice adapter, string macAddress) { var disposables = new CompositeDisposable(); var transport = new ProfinetEthernetTransport(adapter); transport.Open(); transport.AddDisposableTo(disposables); try { System.Net.NetworkInformation.PhysicalAddress deviceAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(macAddress); DCP.BlockErrors err = transport.SendSetSignalRequest(deviceAddress, timeoutInMilliseconds, retries); if (err != DCP.BlockErrors.NoError) { return(Task.FromResult(new SaveResult(false, err.ToString()))); } return(Task.FromResult(new SaveResult(true, err.ToString()))); } catch (Exception e) { return(Task.FromResult(new SaveResult(false, e.Message))); } finally { disposables.Dispose(); } }
public static string GetMac() { var nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); System.Net.NetworkInformation.PhysicalAddress backupAddress = null; foreach (var adapter in nics) { var nit = adapter.NetworkInterfaceType; if (nit == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet || nit == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211) { return(adapter.GetPhysicalAddress().ToString()); } else if (nit != System.Net.NetworkInformation.NetworkInterfaceType.Loopback && nit != System.Net.NetworkInformation.NetworkInterfaceType.Tunnel) { backupAddress = adapter.GetPhysicalAddress(); } } if (backupAddress != null) { return(backupAddress.ToString()); } return("Not found"); }
private int GetAnonymousMachineID() { System.Net.NetworkInformation.PhysicalAddress mac = GetMacAddress(); return(mac != null ? BitConverter.ToInt32(System.Security.Cryptography.MD5.Create().ComputeHash(mac.GetAddressBytes()), 0) : 0); }
public static void SetOneProcessByGuid(Guid guid, BasicEnums.State state) { System.Net.NetworkInformation.PhysicalAddress macAddr = Net.GetMacAddress(); //CheckStatusChannel(); for (int tryCon = 0; tryCon < numberTry; tryCon++) { try { OpenChannel(); objDistributed.SetOneProcessByGuid(guid, state, new RequestorInfo() { macAddr = macAddr.ToString(), machineName = Environment.MachineName }); CloseChannel(); return; } catch (CommunicationException) { //new CustomLog().CommunicationException(ex); //CheckStatusChannel(); throw; } catch (Exception) { //new CustomLog().Exception(ex); throw; } } return; }
// private static void CheckStatusChannel() // { //#if DEBUGPROXY // Console.WriteLine(HelperDebug.GetCurrentMethod()); //#endif // if (objDistributed == null) // { // objDistributed = new ServiceClient(); // } // if (objDistributed.State == CommunicationState.Faulted) // { // //new CustomLog().CommunicationException(new CommunicationException("CommunicationState.Faulted")); // OpenChannel(); // } // else if (objDistributed.State != CommunicationState.Opened) // { // OpenChannel(); // } // } public static ServiceParamWcf GetOneProcessGuiForETL(Guid guid) { System.Net.NetworkInformation.PhysicalAddress macAddr = Net.GetMacAddress(); //CheckStatusChannel(); for (int tryCon = 0; tryCon < numberTry; tryCon++) { try { OpenChannel(); ServiceParamWcf ret = objDistributed.GetOneProcessGuiForETL(guid, new RequestorInfo() { macAddr = macAddr.ToString(), machineName = Environment.MachineName }); CloseChannel(); return(ret); } catch (CommunicationException) { throw; //new CustomLog().CommunicationException(ex); //CheckStatusChannel(); } catch (Exception) { //new CustomLog().Exception(ex); throw; } } return(null); }
public ProfinetUdpTransport(string interface_ip, System.Net.NetworkInformation.PhysicalAddress source_mac) { m_source_mac = source_mac; if (!string.IsNullOrEmpty(interface_ip)) { m_interface_ip = IPAddress.Parse(interface_ip); } m_object_instance = RPC.GenerateObjectInstanceUUID(1, 0, 0x25, 0x120); }
public static string GetFriendlyMAC(System.Net.NetworkInformation.PhysicalAddress mac) { String result, m; m = mac.ToString(); result = m[0].ToString() + m[1].ToString() + " " + m[2].ToString() + m[3].ToString() + " " + m[4].ToString() + m[5].ToString() + " " + m[6].ToString() + m[7].ToString() + " " + m[8].ToString() + m[9].ToString() + " " + m[10].ToString() + m[11].ToString(); return(result); }
public void NpgsqlMacAddress() { System.Net.NetworkInformation.PhysicalAddress local = System.Net.NetworkInformation.PhysicalAddress.Parse("012345ABCDEF"); NpgsqlMacAddress mac = new NpgsqlMacAddress(local); NpgsqlMacAddress mac2 = new NpgsqlMacAddress("01:23-45-aB,cD.eF"); Assert.AreEqual(mac, mac2); Assert.AreEqual(mac.ToString(), mac2.ToString()); }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) { return; } if (m_configuration.m_enableUPnP) { m_upnp = new NetUPnP(this); } InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket BindSocket(false); m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; MWCRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE try { System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } } catch (NotSupportedException) { // not supported; lets just keep the random bytes set above } #endif m_status = NetPeerStatus.Running; } }
public bool TryGetMacVendor(System.Net.NetworkInformation.PhysicalAddress macAddress, out string macVendor) { if (macAddress == null) { macVendor = null; return(false); } else { return(TryGetMacVendor(macAddress.GetAddressBytes(), out macVendor)); } }
public static string sMAC;// = GetMAC(); public static string GetMAC() { string sMAC = ""; System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); if (adapters.Length > 0) { System.Net.NetworkInformation.NetworkInterface adapter = adapters[0]; System.Net.NetworkInformation.PhysicalAddress phadd = adapter.GetPhysicalAddress(); sMAC = phadd.ToString(); } return(sMAC); }
public static int Encode(System.IO.Stream buffer, System.Net.NetworkInformation.PhysicalAddress destination, System.Net.NetworkInformation.PhysicalAddress source, Type type) { //destination DCP.EncodeOctets(buffer, destination.GetAddressBytes()); //source DCP.EncodeOctets(buffer, source.GetAddressBytes()); //type DCP.EncodeU16(buffer, (ushort)type); return(14); }
private string GetNICString() { // Use the physical address (MAC) of the first network interface that has a non-null MAC address. System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface nic in nics) { System.Net.NetworkInformation.PhysicalAddress mac = nic.GetPhysicalAddress(); if (mac != System.Net.NetworkInformation.PhysicalAddress.None) { return(mac.ToString()); } } return(string.Empty); }
public static Packet buildIpV4( MacAddress srcAddress_mac, MacAddress dstAddrress_mac, IpV4Packet.Builder builder_ipv4) { org.pcap4j.packet.Packet.Builder builder = null; EthernetPacketType etherType; //EtherType etherType = null; Packet p = null; if (ppp) { etherType = EthernetPacketType.PointToPointProtocolOverEthernetSessionStage; //etherType = EtherType.PPPOE_SESSION_STAGE; UnknownPacket.Builder pppBuilder = new UnknownPacket.Builder(); byte[] ipData = builder_ipv4.build().getRawData(); byte[] lenb = new byte[2]; ByteShortConvert.toByteArray((short)(ipData.length + 2), lenb, 0); byte[] pppHead = new byte[8]; System.arraycopy(pppHead_static, 0, pppHead, 0, pppHead.length); System.arraycopy(lenb, 0, pppHead, 4, 2); byte[] newData = new byte[pppHead.length + ipData.length]; System.arraycopy(pppHead, 0, newData, 0, pppHead.length); System.arraycopy(ipData, 0, newData, 8, ipData.length); pppBuilder.rawData(newData); builder = pppBuilder; } else { etherType = EtherType.IPV4; builder = builder_ipv4; } EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); etherBuilder.dstAddr(dstAddrress_mac) .srcAddr(srcAddress_mac) .type(etherType) .payloadBuilder(builder) .paddingAtBuild(true); p = etherBuilder.build(); return(p); }
public static arpResult Resolve(System.Net.IPAddress dest, LibPcapLiveDevice dev = null) { if (dev == null) { dev = device.directLinkDevice(dest); } ARP arper = new ARP(dev); Stopwatch sw = Stopwatch.StartNew(); System.Net.NetworkInformation.PhysicalAddress mac = arper.Resolve(dest); sw.Stop(); long ms = sw.ElapsedMilliseconds; return(new arpResult { dest = dest, mac = mac, elapsedMs = ms }); }
/// <summary> /// 이더넷 Mac Address 를 가져온다. /// </summary> /// <returns>Mac Address</returns> public static string GetMACAddress() { string MacAddress = ""; System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface adapter in adapters) { System.Net.NetworkInformation.PhysicalAddress pa = adapter.GetPhysicalAddress(); if (pa != null && !pa.ToString().Equals("")) { MacAddress = pa.ToString(); break; } } return(MacAddress); }
virtual PPacket Parsing(Packet packet, TimeSpan time, int len) { var ethernetPacket = packet.Extract <PacketDotNet.EthernetPacket>(); var arpPacket = packet.Extract <PacketDotNet.ArpPacket>(); System.Net.IPAddress srcId = null, dstId = null; System.Net.NetworkInformation.PhysicalAddress srcPort = ethernetPacket.SourceHardwareAddress; System.Net.NetworkInformation.PhysicalAddress dstPort = ethernetPacket.DestinationHardwareAddress; if (arpPacket != null) { dstId = arpPacket.TargetProtocolAddress; srcId = arpPacket.SenderProtocolAddress; } PPacket protocol = new PPacket("Ethernet", Convert.ToString(time.Hours) + ":" + Convert.ToString(time.Minutes) + ":" + Convert.ToString(time.Seconds) + " " + Convert.ToString(time.Milliseconds), Convert.ToString(len), Convert.ToString(srcId), Convert.ToString(dstId), Convert.ToString(srcPort), Convert.ToString(dstPort), "-"); return(protocol); }
public string MAC_PhysicalAddressToString(System.Net.NetworkInformation.PhysicalAddress mac, char?separator) { var macString = mac.ToString(); if (separator == null) { return(macString); } var friendlyMac = new StringBuilder(); for (var i = 0; i < macString.Length; i += 2) { if (i > 0) { friendlyMac.Append(separator); } friendlyMac.Append(macString.Substring(i, 2).ToUpper()); } return(friendlyMac.ToString()); }
public Task <SaveResult> SendSettings(ICaptureDevice adapter, string macAddress, Device newSettings, bool permanent) { var disposables = new CompositeDisposable(); var transport = new ProfinetEthernetTransport(adapter); transport.Open(); transport.AddDisposableTo(disposables); try { System.Net.NetworkInformation.PhysicalAddress deviceAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(macAddress); DCP.BlockErrors err = transport.SendSetNameRequest(deviceAddress, timeoutInMilliseconds, retries, newSettings.Name, permanent); if (err != DCP.BlockErrors.NoError) { return(Task.FromResult(new SaveResult(false, err.ToString()))); } System.Net.IPAddress ip = System.Net.IPAddress.Parse(newSettings.IP); System.Net.IPAddress subnet = System.Net.IPAddress.Parse(newSettings.SubnetMask); System.Net.IPAddress gateway = System.Net.IPAddress.Parse(newSettings.Gateway); err = transport.SendSetIpRequest(deviceAddress, timeoutInMilliseconds, retries, ip, subnet, gateway, permanent); if (err != DCP.BlockErrors.NoError) { return(Task.FromResult(new SaveResult(false, err.ToString()))); } return(Task.FromResult(new SaveResult(true, err.ToString()))); } catch (Exception e) { return(Task.FromResult(new SaveResult(false, e.Message))); } finally { disposables.Dispose(); } }
public void SetUp() { var devices = CaptureDeviceList.Instance; // Sniff all devices foreach (var device in devices) { device.Open(DeviceMode.Promiscuous); device.Filter = "tcp portrange 8383-9000"; Logger.WriteLine("[DEBUG] Set filter for {0}", device.Description); device.OnPacketArrival += device_OnPacketArrival; device.StartCapture(); _devices.Add(device); System.Net.NetworkInformation.PhysicalAddress mac = null; try { mac = device.MacAddress; } catch { Logger.WriteLine("Unable to get mac address!!!"); } if (device.LinkType != LinkLayers.Ethernet) { Logger.WriteLine("Skipped sniffing {0} ({1})", device.Description, mac); StopCapture(device); } else { Logger.WriteLine("Started sniffing {0} ({1})", device.Description, mac); } } }
static Packet createSync( MacAddress srcAddress_mac, MacAddress dstAddrress_mac, Inet4Address srcAddress, short srcPort, Inet4Address dstAddress, short dstPort, int sequence, short ident) { TcpPacket.Builder builder_tcp = new TcpPacket.Builder(); //builder_tcp.payloadBuilder(new UnknownPacket.Builder().rawData(new byte[0])); builder_tcp.correctChecksumAtBuild(true); builder_tcp.correctLengthAtBuild(true); builder_tcp.paddingAtBuild(true); //builder_tcp.ack(true); //builder_tcp.acknowledgmentNumber(ack_sequence); //builder_tcp.checksum(tcpHeader.getChecksum()); //builder_tcp.dataOffset((byte) 8); builder_tcp.dstAddr(dstAddress); builder_tcp.dstPort(new TcpPort(dstPort, "")); //builder_tcp.fin(tcpHeader.getFin()); TcpNoOperationOption nop = TcpNoOperationOption.getInstance(); ArrayList <TcpOption> tcp_options = new ArrayList <TcpOption>(); TcpMaximumSegmentSizeOption seg_option = new TcpMaximumSegmentSizeOption.Builder().maxSegSize(mtu).correctLengthAtBuild(true).build(); tcp_options.add(seg_option); tcp_options.add(nop); TcpWindowScaleOption win_option = new TcpWindowScaleOption.Builder().shiftCount((byte)6).correctLengthAtBuild(true).build(); tcp_options.add(win_option); tcp_options.add(nop); tcp_options.add(nop); TcpSackPermittedOption sack_permit_option = TcpSackPermittedOption.getInstance(); tcp_options.add(sack_permit_option); builder_tcp.options(tcp_options); //builder_tcp.padding(tcpHeader.getPadding()); builder_tcp.psh(false); builder_tcp.reserved((byte)0); builder_tcp.rst(false); builder_tcp.sequenceNumber(sequence); builder_tcp.srcAddr(srcAddress); builder_tcp.srcPort(new TcpPort(srcPort, "")); builder_tcp.syn(true); builder_tcp.urg(false); //builder_tcp.urgentPointer(tcpHeader.getUrgentPointer()); builder_tcp.window(window); IpV4Packet.Builder builder_ipv4 = new IpV4Packet.Builder(); builder_ipv4.correctChecksumAtBuild(true); builder_ipv4.correctLengthAtBuild(true); builder_ipv4.paddingAtBuild(true); builder_ipv4.dstAddr(dstAddress); builder_ipv4.dontFragmentFlag(true); builder_ipv4.fragmentOffset((short)0); //builder_ipv4.headerChecksum(ipV4Header.getHeaderChecksum()); //short identification= Math.abs(random.nextInt(Short.MAX_VALUE)); builder_ipv4.identification(ident); builder_ipv4.ihl((byte)5); //builder_ipv4.moreFragmentFlag(ipV4Header.getMoreFragmentFlag()); //builder_ipv4.options(ipV4Header.getOptions()); //builder_ipv4.padding(ipV4Header.getPadding()); builder_ipv4.protocol(IpNumber.TCP); // builder_ipv4.reservedFlag(ipV4Header.getReservedFlag()); builder_ipv4.srcAddr(srcAddress); builder_ipv4.tos(IpV4Rfc1349Tos.newInstance((byte)0)); //builder_ipv4.totalLength( 52); builder_ipv4.ttl(ttl); builder_ipv4.version(IpVersion.IPV4); builder_ipv4.payloadBuilder(builder_tcp); // Packet p = buildIpV4(srcAddress_mac, dstAddrress_mac, builder_ipv4); // IpV4Packet p4=builder_ipv4.build(); // TcpPacket tcpPacket=builder_tcp.build(); //selfAckTable.add(identification); //System.out.println("自定义确认 "+" identification "+identification+" ack_sequence "+ack_sequence+" # "+tcpPacket.getHeader()); return(p); }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) { return; } if (m_configuration.m_enableUPnP) { m_upnp = new NetUPnP(this); } InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket IPEndPoint iep = null; iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize; m_socket.SendBufferSize = m_configuration.SendBufferSize; m_socket.Blocking = false; m_socket.Bind(ep); try { const uint IOC_IN = 0x80000000; const uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; m_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); } catch { // ignore; SIO_UDP_CONNRESET not supported on this platform } IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound); m_listenPort = boundEp.Port; m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; NetRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE try { System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } } catch (NotSupportedException) { // not supported; lets just keep the random bytes set above } #endif byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0); m_status = NetPeerStatus.Running; } }
internal DhcpPacket(Frame parentFrame, int packetStartIndex, int packetEndIndex) : base(parentFrame, packetStartIndex, packetEndIndex, "DHCP (Bootstrap protocol)") { this.opCode = (OpCodeValue)parentFrame.Data[packetStartIndex]; if (!this.ParentFrame.QuickParse) { base.Attributes.Add("OpCode", this.OpCode.ToString()); } //skip hardware type //skip hlen //skip hops this.transactionID = Utils.ByteConverter.ToUInt32(parentFrame.Data, packetStartIndex + 4); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Transaction ID", "0x" + this.transactionID.ToString("X2")); } this.secondsElapsed = Utils.ByteConverter.ToUInt16(parentFrame.Data, packetStartIndex + 8); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Seconds elapsed", this.secondsElapsed.ToString()); } //skip flags (unused in BOOTP) byte[] ipAddrArray = new byte[4]; Array.ConstrainedCopy(parentFrame.Data, packetStartIndex + 12, ipAddrArray, 0, 4); clientIpAddress = new System.Net.IPAddress(ipAddrArray); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Client IP Address", this.clientIpAddress.ToString()); } Array.ConstrainedCopy(parentFrame.Data, packetStartIndex + 16, ipAddrArray, 0, 4);//do I need to create a new byte[4] before this one? yourIpAddress = new System.Net.IPAddress(ipAddrArray); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Your IP Address", this.yourIpAddress.ToString()); } Array.ConstrainedCopy(parentFrame.Data, packetStartIndex + 20, ipAddrArray, 0, 4); serverIpAddress = new System.Net.IPAddress(ipAddrArray); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Server IP Address", this.serverIpAddress.ToString()); } Array.ConstrainedCopy(parentFrame.Data, packetStartIndex + 24, ipAddrArray, 0, 4); gatewayIpAddress = new System.Net.IPAddress(ipAddrArray); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Gateway IP Address", this.gatewayIpAddress.ToString()); } byte[] macAddrArray = new byte[6]; Array.ConstrainedCopy(parentFrame.Data, packetStartIndex + 28, macAddrArray, 0, 6); clientMacAddress = new System.Net.NetworkInformation.PhysicalAddress(macAddrArray); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("Client MAC Address", this.clientMacAddress.ToString()); } //skip extra 10 bytes of client hardware address //Skip 192 octets of 0's. BOOTP legacy //64 - optional server host name //128 - boot file name //skip magic cookie (4 bytes) optionList = new List <Option>(); int index = packetStartIndex + 240;//0x011A - 0x002A = 0xF0 while (index < packetEndIndex) { Option option = new Option(parentFrame.Data, index); if (option.OptionCode == 0xff)//check for "End Option" { break; } if (option.OptionCode == 3)//Default Gateway (router) { this.gatewayIpAddress = new System.Net.IPAddress(option.OptionValue); } else if (option.OptionCode == 53)//extract the DHCP Message Type: 1=Discover, 2=Offer, 3=Request, 5=Ack, 8=Inform { if (option.OptionValue != null && option.OptionValue.Length == 1) { this.dhcpMessageType = option.OptionValue[0]; } } optionList.Add(option); if (!this.ParentFrame.QuickParse) { base.Attributes.Add("DHCP Options", option.OptionCode.ToString()); } index += option.OptionValue.Length + 2; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { System.Net.NetworkInformation.PhysicalAddress _mac = (System.Net.NetworkInformation.PhysicalAddress)value; writer.WriteValue(_mac.ToString()); }
/// <summary> /// Wake up a turned off computer over LAN. /// </summary> /// <param name="mac">MAC addres to send to magic packet.</param> /// <param name="port">7 and 9 are default ports for Wake on LAN</param> public void WakeOnLAN(System.Net.NetworkInformation.PhysicalAddress mac, ushort port) { WakeOnLAN(macAddressConverter.MAC_PhysicalAddressToString(mac), port); }
static List <ArpEntry> ScanTarget(IPAddress ip, ScanOptions options) { List <ArpEntry> results = new List <ArpEntry>(); OctetString community = new OctetString(options.Community); List <Variable> ARPTypeResult = new List <Variable>(); List <Variable> ARPIPResult = new List <Variable>(); List <Variable> ARPPhysAddrResult = new List <Variable>(); try { Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.4"), ARPTypeResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.2"), ARPPhysAddrResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.3"), ARPIPResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); } catch (Lextm.SharpSnmpLib.Messaging.TimeoutException te) { Console.WriteLine("Request to {0} timed out, skipping... : {1}", ip, te); return(results); } foreach (Variable v in ARPTypeResult) { if (v.Data.Equals(new Integer32(4)) && options.ProcessStaticARPEntries == false) { continue; } else if (v.Data.Equals(new Integer32(3)) && options.ProcessDynamicARPEntries == false) { continue; } else if (v.Data.Equals(new Integer32(2)) && options.ProcessInvalidARPEntries == false) { continue; } else if (v.Data.Equals(new Integer32(1)) && options.ProcessOtherARPEntries == false) { continue; } uint[] numID = v.Id.ToNumerical().ToArray(); numID[9] = 3; ObjectIdentifier IPID = new ObjectIdentifier(numID); ISnmpData IPData = ARPIPResult.Where(i => i.Id == IPID).Select(x => x).Single().Data; numID[9] = 2; ObjectIdentifier PhysAddrID = new ObjectIdentifier(numID); ISnmpData PhysAddrData = ARPPhysAddrResult.Where(i => i.Id == PhysAddrID).Select(x => x).Single().Data; System.Net.NetworkInformation.PhysicalAddress mac = new System.Net.NetworkInformation.PhysicalAddress(PhysAddrData.ToBytes().Skip(2).ToArray()); ArpEntry entry = new ArpEntry(IPAddress.Parse(IPData.ToString()), mac); results.Add(entry); } return(results); }
// paket information private void ListView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { string protocol = e.Item.SubItems[4].Text; int key = Int32.Parse(e.Item.SubItems[0].Text); Packet packet; bool getPacket = capturedPackets_list.TryGetValue(key, out packet); switch (protocol) { case protocolTCP: if (getPacket) { var tcpPacket = (TcpPacket)packet.Extract(typeof(TcpPacket)); if (tcpPacket != null) { int srcPort = tcpPacket.SourcePort; int dstPort = tcpPacket.DestinationPort; var checksum = tcpPacket.Checksum; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: TCP" + "\r\nSource port:" + srcPort + "\r\nDestination port: " + dstPort + "\r\nTCP header size: " + tcpPacket.DataOffset + "\r\nWindow size: " + tcpPacket.WindowSize + // bytes that the receiver is willing to receive "\r\nChecksum:" + checksum.ToString() + (tcpPacket.ValidChecksum ? ",valid" : ",invalid") + "\r\nTCP checksum: " + (tcpPacket.ValidTCPChecksum ? ",valid" : ",invalid") + "\r\nSequence number: " + tcpPacket.SequenceNumber.ToString() + "\r\nAcknowledgment number: " + tcpPacket.AcknowledgmentNumber + (tcpPacket.Ack ? ",valid" : ",invalid") + // flags "\r\nUrgent pointer: " + (tcpPacket.Urg ? "valid" : "invalid") + "\r\nACK flag: " + (tcpPacket.Ack ? "1" : "0") + // indicates if the AcknowledgmentNumber is valid "\r\nPSH flag: " + (tcpPacket.Psh ? "1" : "0") + // push 1 = the receiver should pass the data to the app immidiatly, don't buffer it "\r\nRST flag: " + (tcpPacket.Rst ? "1" : "0") + // reset 1 is to abort existing connection // SYN indicates the sequence numbers should be synchronized between the sender and receiver to initiate a connection "\r\nSYN flag: " + (tcpPacket.Syn ? "1" : "0") + // closing the connection with a deal, host_A sends FIN to host_B, B responds with ACK // FIN flag indicates the sender is finished sending "\r\nFIN flag: " + (tcpPacket.Fin ? "1" : "0") + "\r\nECN flag: " + (tcpPacket.ECN ? "1" : "0") + "\r\nCWR flag: " + (tcpPacket.CWR ? "1" : "0") + "\r\nNS flag: " + (tcpPacket.NS ? "1" : "0"); } } break; case protocolUDP: if (getPacket) { var udpPacket = (UdpPacket)packet.Extract(typeof(UdpPacket)); if (udpPacket != null) { int srcPort = udpPacket.SourcePort; int dstPort = udpPacket.DestinationPort; var checksum = udpPacket.Checksum; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: UDP" + "\r\nSource port:" + srcPort + "\r\nDestination port: " + dstPort + "\r\nChecksum:" + checksum.ToString() + " valid: " + udpPacket.ValidChecksum + "\r\nValid UDP checksum: " + udpPacket.ValidUDPChecksum; } } break; case protocolARP: if (getPacket) { var arpPacket = (ARPPacket)packet.Extract(typeof(ARPPacket)); if (arpPacket != null) { System.Net.IPAddress senderAddress = arpPacket.SenderProtocolAddress; System.Net.IPAddress targerAddress = arpPacket.TargetProtocolAddress; System.Net.NetworkInformation.PhysicalAddress senderHardwareAddress = arpPacket.SenderHardwareAddress; System.Net.NetworkInformation.PhysicalAddress targerHardwareAddress = arpPacket.TargetHardwareAddress; textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: ARP" + "\r\nHardware address length:" + arpPacket.HardwareAddressLength + "\r\nProtocol address length: " + arpPacket.ProtocolAddressLength + "\r\nOperation: " + arpPacket.Operation.ToString() + // ARP request or ARP reply ARP_OP_REQ_CODE, ARP_OP_REP_CODE "\r\nSender protocol address: " + senderAddress + "\r\nTarget protocol address: " + targerAddress + "\r\nSender hardware address: " + senderHardwareAddress + "\r\nTarget hardware address: " + targerHardwareAddress; } } break; case protocolIcmp: if (getPacket) { var icmpPacket = (ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)); if (icmpPacket != null) { textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: ICMP v4" + "\r\nType Code: 0x" + icmpPacket.TypeCode.ToString("x") + "\r\nChecksum: " + icmpPacket.Checksum.ToString("x") + "\r\nID: 0x" + icmpPacket.ID.ToString("x") + "\r\nSequence number: " + icmpPacket.Sequence.ToString("x"); } } break; case protocolIgmp: if (getPacket) { var igmpPacket = (IGMPv2Packet)packet.Extract(typeof(IGMPv2Packet)); if (igmpPacket != null) { textBox2.Text = ""; textBox2.Text = "Packet number: " + key + " Type: IGMP v2" + "\r\nType: " + igmpPacket.Type + "\r\nGroup address: " + igmpPacket.GroupAddress + "\r\nMax response time" + igmpPacket.MaxResponseTime; } } break; default: textBox2.Text = ""; break; } }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) { return; } if (m_configuration.m_enableUPnP) { m_upnp = new NetUPnP(this); } InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket BindSocket(false); m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; MWCRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE try { System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } } catch (NotSupportedException) { // not supported; lets just keep the random bytes set above } #endif IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); m_uniqueIdentifier = BitConverter.ToInt64(NetUtility.CreateSHA1Hash(combined), 0); m_status = NetPeerStatus.Running; } }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) { return; } if (m_configuration.m_enableUPnP) { m_upnp = new NetUPnP(this); } InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket IPEndPoint iep = null; iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port); EndPoint ep = (EndPoint)iep; m_socket = new PlatformSocket(); m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize; m_socket.SendBufferSize = m_configuration.SendBufferSize; m_socket.Blocking = false; m_socket.Bind(ep); m_socket.Setup(); IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound); m_listenPort = boundEp.Port; m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; NetRandom.Instance.NextBytes(macBytes); #if IS_FULL_NET_AVAILABLE try { System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } } catch (NotSupportedException) { // not supported; lets just keep the random bytes set above } #endif byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); #if WINDOWS_PHONE SHA1 s = new SHA1Managed(); m_uniqueIdentifier = BitConverter.ToInt64(s.ComputeHash(combined), 0); #else m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0); #endif m_status = NetPeerStatus.Running; } }
static List<ArpEntry> ScanTarget(IPAddress ip, ScanOptions options) { List<ArpEntry> results = new List<ArpEntry>(); OctetString community = new OctetString(options.Community); List<Variable> ARPTypeResult = new List<Variable>(); List<Variable> ARPIPResult = new List<Variable>(); List<Variable> ARPPhysAddrResult = new List<Variable>(); try { Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.4"), ARPTypeResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.2"), ARPPhysAddrResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); Messenger.BulkWalk(VersionCode.V2, new IPEndPoint(ip, 161), new OctetString(options.Community), new ObjectIdentifier("1.3.6.1.2.1.4.22.1.3"), ARPIPResult, options.SNMPTimeout, 10, WalkMode.WithinSubtree, null, null); } catch(Lextm.SharpSnmpLib.Messaging.TimeoutException te) { Console.WriteLine("Request to {0} timed out, skipping... : {1}", ip, te); return results; } foreach (Variable v in ARPTypeResult) { if (v.Data.Equals(new Integer32(4)) && options.ProcessStaticARPEntries == false) continue; else if (v.Data.Equals(new Integer32(3)) && options.ProcessDynamicARPEntries == false) continue; else if (v.Data.Equals(new Integer32(2)) && options.ProcessInvalidARPEntries == false) continue; else if (v.Data.Equals(new Integer32(1)) && options.ProcessOtherARPEntries == false) continue; uint[] numID = v.Id.ToNumerical().ToArray(); numID[9] = 3; ObjectIdentifier IPID = new ObjectIdentifier(numID); ISnmpData IPData = ARPIPResult.Where(i => i.Id == IPID).Select(x => x).Single().Data; numID[9] = 2; ObjectIdentifier PhysAddrID = new ObjectIdentifier(numID); ISnmpData PhysAddrData = ARPPhysAddrResult.Where(i => i.Id == PhysAddrID).Select(x => x).Single().Data; System.Net.NetworkInformation.PhysicalAddress mac = new System.Net.NetworkInformation.PhysicalAddress(PhysAddrData.ToBytes().Skip(2).ToArray()); ArpEntry entry = new ArpEntry(IPAddress.Parse(IPData.ToString()), mac); results.Add(entry); } return results; }
static Packet createDataPacket( MacAddress srcAddress_mac, MacAddress dstAddrress_mac, Inet4Address srcAddress, short srcPort, Inet4Address dstAddress, short dstPort, int sequence, int ack, byte[] data, short ident) { Packet p = null; TcpPacket.Builder builder_tcp = new TcpPacket.Builder(); builder_tcp.payloadBuilder(new UnknownPacket.Builder().rawData(data)); builder_tcp.correctChecksumAtBuild(true); builder_tcp.correctLengthAtBuild(true); builder_tcp.paddingAtBuild(true); builder_tcp.ack(true); builder_tcp.acknowledgmentNumber(ack); //builder_tcp.checksum(tcpHeader.getChecksum()); //builder_tcp.dataOffset((byte)8); builder_tcp.dstAddr(dstAddress); builder_tcp.dstPort(new TcpPort(dstPort, "")); builder_tcp.fin(false); //builder_tcp.options(tcpHeader.getOptions()); //builder_tcp.padding(tcpHeader.getPadding()); builder_tcp.psh(false); builder_tcp.reserved((byte)0); builder_tcp.rst(false); builder_tcp.sequenceNumber(sequence); builder_tcp.srcAddr(srcAddress); builder_tcp.srcPort(new TcpPort(srcPort, "")); builder_tcp.syn(false); builder_tcp.urg(false); //builder_tcp.urgentPointer(tcpHeader.getUrgentPointer()); builder_tcp.window(window); IpV4Packet.Builder builder_ipv4 = new IpV4Packet.Builder(); builder_ipv4.correctChecksumAtBuild(true); builder_ipv4.correctLengthAtBuild(true); builder_ipv4.dontFragmentFlag(true); builder_ipv4.paddingAtBuild(true); builder_ipv4.dstAddr(dstAddress); builder_ipv4.fragmentOffset((short)0); //builder_ipv4.headerChecksum(ipV4Header.getHeaderChecksum()); //short identification= Math.abs(random.nextInt(Short.MAX_VALUE)); //identification=ident; builder_ipv4.identification(ident); builder_ipv4.ihl((byte)5); builder_ipv4.moreFragmentFlag(false); //builder_ipv4.options(ipV4Header.getOptions()); //builder_ipv4.padding(ipV4Header.getPadding()); builder_ipv4.protocol(IpNumber.TCP); //builder_ipv4.reservedFlag(ipV4Header.getReservedFlag()); builder_ipv4.srcAddr(srcAddress); builder_ipv4.tos(IpV4Rfc1349Tos.newInstance((byte)0)); //builder_ipv4.totalLength( 52); builder_ipv4.ttl(ttl); builder_ipv4.version(IpVersion.IPV4); builder_ipv4.payloadBuilder(builder_tcp); p = buildIpV4(srcAddress_mac, dstAddrress_mac, builder_ipv4); return(p); }