private static void BroadcastMagicPacket(PhysicalAddress physicalAddress, IPAddress broadcastIPAddress) { if (physicalAddress == null) throw new ArgumentNullException(nameof(physicalAddress)); var physicalAddressBytes = physicalAddress.GetAddressBytes(); var packet = new byte[17 * 6]; for (var i = 0; i < 6; i++) { packet[i] = 0xFF; } for (var i = 1; i <= 16; i++) { for (var j = 0; j < 6; j++) { packet[i * 6 + j] = physicalAddressBytes[j]; } } using (var client = new UdpClient()) { client.Connect(broadcastIPAddress ?? IPAddress.Broadcast, 40000); client.Send(packet, packet.Length); } }
public MacRule(PacketStatus ps, PhysicalAddress mac, Direction direction, bool log, bool notify) { this.ps = ps; this.mac = mac.GetAddressBytes(); this.direction = direction; this.log = log; this.notify = notify; }
/// <summary> /// Convert to a formatted string containing the address contained in this instance. /// </summary> /// <param name="address">The instance of address.</param> /// <returns>Returns the formatted String representation of the address of this instance.</returns> public static String ToFormattedString(this PhysicalAddress address) { Byte[] addressBytes = address.GetAddressBytes(); if (addressBytes.Length != 6) { throw new FormatException("PhysicalAddress format is illegal."); } return(String.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3], addressBytes[4], addressBytes[5])); }
/// <summary>Sends a Wake On LAN signal (magic packet) to a client.</summary> /// <param name="target">Destination <see cref="IPEndPoint"/>.</param> /// <param name="macAddress">The MAC address of the designated client.</param> /// <param name="password">The SecureOn password of the client.</param> /// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception> /// <exception cref="SocketException">An error occurred when accessing the socket. See Remarks section of <see cref="UdpClient.Send(byte[], int, IPEndPoint)"/> for more information.</exception> public static void Send(IPEndPoint target, PhysicalAddress macAddress, SecureOnPassword password) { if (macAddress == null) throw new ArgumentNullException(nameof(macAddress)); byte[] passwordBuffer = password?.GetPasswordBytes(); byte[] packet = GetWolPacket(macAddress.GetAddressBytes(), passwordBuffer); SendPacket(target, packet); }
/// <summary> /// Creates a string from a Physical address in the format "xx:xx:xx:xx:xx:xx" /// </summary> /// <param name="address"> /// A <see cref="PhysicalAddress"/> /// </param> /// <returns> /// A <see cref="System.String"/> /// </returns> public static string PrintMACAddress(PhysicalAddress address) { byte[] bytes = address.GetAddressBytes(); string output = ""; for (int i = 0; i < bytes.Length; i++) { output += bytes[i].ToString("x").PadLeft(2, '0') + ":"; } return output.TrimEnd(':'); }
public static String FormatMacAddress(PhysicalAddress macAddress) { String str = String.Empty; if (macAddress != null) { str = BitConverter.ToString (macAddress.GetAddressBytes ()).Replace ('-', ':'); } return str; }
public static void Test() { Console.WriteLine("++++++++++++++++++System.Net.NetworkInformation.PhysicalAddress++++++++++++++++++"); PhysicalAddress address = PhysicalAddress.Parse("00-00-00-00-00-00"); Byte [] bytes = address.GetAddressBytes(); String bytesString = "Bytes:"; for (int i = 0; i < bytes.Length; ++i) { bytesString += String.Format("{0:X2} ", bytes[i]); } Console.WriteLine(bytesString); Console.WriteLine("PhysicalAddress.ToString:{0}", address.ToString()); Console.WriteLine("PhysicalAddress.ToFormattedString:{0}", address.ToFormattedString()); }
/// <summary> /// Gets the MacAdress. /// </summary> /// <param name="This">This PhysicalAddress.</param> /// <returns>The mac adress string, delimited with ":"</returns> public static string MacAdress(this PhysicalAddress This) { Contract.Requires(This != null); return(string.Join(":", This.GetAddressBytes().Select(b => string.Format("{0:X2}", b)))); }
//Build the command packet in bytes according to the value of each field public static byte[] GetCommandPacket(SimulatorCommand sCommand, PhysicalAddress destMAC = null) { //If the command packet is for local NIC, we should set the MAC field to all 0 //If the command packet is for remote NIC, we should set the MAC field to remote MAC address byte cmdByte = 0x00; byte[] macInBytes = null; switch (sCommand) { case SimulatorCommand.LoseLocalConnection: cmdByte = BuildCommandByte((byte)NESNICLocation.Local, (byte)NESCommand.Lose); macInBytes = localUsedMac; break; case SimulatorCommand.RestoreLocalConnection: cmdByte = BuildCommandByte((byte)NESNICLocation.Local, (byte)NESCommand.Restore); macInBytes = localUsedMac; break; case SimulatorCommand.LoseRemoteConnection: cmdByte = BuildCommandByte((byte)NESNICLocation.Remote, (byte)NESCommand.Lose); if (destMAC != null) macInBytes = destMAC.GetAddressBytes(); break; case SimulatorCommand.RestoreRemoteConnection: cmdByte = BuildCommandByte((byte)NESNICLocation.Remote, (byte)NESCommand.Restore); if (destMAC != null) macInBytes = destMAC.GetAddressBytes(); break; default: break; } if (cmdByte == paddingByte || macInBytes == null) return null; int packetLength = guid.Length + 2 + macInBytes.Length; //The Length of Command Packet = GUID(16) + paddingByte(1) + commandByte(1) + MAC(1) int curIdx = 0; byte[] res = new byte[packetLength]; Array.Copy(guid, res, guid.Length); curIdx = guid.Length; res[curIdx++] = paddingByte; res[curIdx++] = cmdByte; Array.Copy(macInBytes, 0, res, curIdx, macInBytes.Length); curIdx += macInBytes.Length; return res; }
/** * Method for generating time based UUIDs. * * @param addr Hardware address (802.1) to use for generating * spatially unique part of UUID. If system has more than one NIC, * any address is usable. If no NIC is available (or its address * not accessible; often the case with java apps), a randomly * generated broadcast address is acceptable. If so, use the * alternative method that takes no arguments. * * @return UUID generated using time based method */ public UUID GenerateTimeBasedUUID(PhysicalAddress addr) { byte[] contents = new byte[16]; addr.GetAddressBytes().CopyTo(contents, 10); lock (mTimerLock) { if (mTimer == null) { mTimer = new UUIDTimer(GetRandomNumberGenerator()); } mTimer.GetTimestamp(contents); } return new UUID(UUID.TYPE_TIME_BASED, contents); }
/// <summary> /// Sendet ein Wake-On-LAN-Signal an einen Client. /// </summary> /// <param name="target">Der Ziel-IPEndPoint.</param> /// <param name="macAddress">Die MAC-Adresse des Clients.</param> /// <exception cref="System.ArgumentNullException">macAddress ist null.</exception> /// <exception cref="System.Net.Sockets.SocketException">Fehler beim Zugriff auf den Socket. Weitere Informationen finden Sie im Abschnitt "Hinweise".</exception> public static void Send(IPEndPoint target, PhysicalAddress macAddress) { if (macAddress == null) throw new ArgumentNullException("macAddress"); byte[] packet = GetWolPacket(macAddress.GetAddressBytes()); SendPacket(target, packet); }
public MacAddrConvertable(PhysicalAddress Mac) : this(Mac.GetAddressBytes()) { }
private byte[] CreateServerIdentifierValue(PhysicalAddress mac) { using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(ms)) { writer.Write((byte)0x00); // duid type writer.Write((byte)0x01); // duid type writer.Write((byte)0x00); // hardware type writer.Write((byte)0x01); // hardware type writer.Write(DateTo4BytesString(DateTime.Now)); writer.Write(mac.GetAddressBytes());//mac } return ms.ToArray(); } }
/** * Method for generating time based UUIDs. * * @param addr Hardware address (802.1) to use for generating * spatially unique part of UUID. If system has more than one NIC, * any address is usable. If no NIC is available (or its address * not accessible; often the case with java apps), a randomly * generated broadcast address is acceptable. If so, use the * alternative method that takes no arguments. * * @return UUID generated using time based method */ public UUID GenerateTimeBasedUUID(PhysicalAddress addr) { byte[] contents = new byte[16]; var addrBytes = addr.GetAddressBytes(); Array.ConstrainedCopy(addrBytes, 0, contents, 10, addrBytes.Length); lock (mTimerLock) { if (mTimer == null) { mTimer = new UUIDTimer(GetRandomNumberGenerator()); } mTimer.GetTimestamp(contents); } return new UUID(UUID.TYPE_TIME_BASED, contents); }
private static IEnumerable <Tuple <PhysicalAddress, IPAddress> > _GetArpCache() { // The number of bytes needed. var bytesNeeded = 0U; // The result from the API call. var result = NativeMethods.GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != NativeMethods.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. var buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem((int)bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = NativeMethods.GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { throw new Win32Exception(result); } // Now we have the buffer, we have to marshal it. We can read // the first 4 bytes to get the length of the buffer. var entries = Marshal.ReadInt32(buffer); // Increment the memory pointer by the size of the int. var currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int))); // Cycle through the entries. for (var index = 0; index < entries; index++) { // Call PtrToStructure, getting the structure information. var row = (NativeMethods.MIB_IPNETROW)Marshal.PtrToStructure( new IntPtr(currentBuffer.ToInt64() + index * Marshal.SizeOf(typeof(NativeMethods.MIB_IPNETROW))), typeof(NativeMethods.MIB_IPNETROW) ); var ip = new IPAddress(BitConverter.GetBytes(row.dwAddr)); var physicalAddress = new PhysicalAddress(new[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5, //row.mac6, //row.mac7, }); if (physicalAddress.GetAddressBytes().Any(b => b != 0)) { yield return(Tuple.Create(physicalAddress, ip)); } } } finally { // Release the memory. if (buffer != IntPtr.Zero) { NativeMethods.FreeMibTable(buffer); } } }
/// <summary> /// Pairs the current device to the provided Bluetooth host. /// </summary> /// <param name="master">The MAC address of the host.</param> /// <returns>True on success, false otherwise.</returns> public override bool Pair(PhysicalAddress master) { var transfered = 0; var host = master.GetAddressBytes(); byte[] buffer = { 0x00, 0x00, host[0], host[1], host[2], host[3], host[4], host[5] }; if (!SendTransfer(UsbHidRequestType.HostToDevice, UsbHidRequest.SetReport, 0x03F5, buffer, ref transfered)) return false; HostAddress = master; return true; }
static string GetMacStrFromPhysical(PhysicalAddress pa) { byte[] macbyte = pa.GetAddressBytes(); string pastr = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}{4:X2}{5:X2}", macbyte[0], macbyte[1], macbyte[2], macbyte[3], macbyte[4], macbyte[5]); return pastr; }
public string FormatMacAddress(PhysicalAddress Input) { string Output = ""; byte[] bytes = Input.GetAddressBytes(); for (int i = 0; i < bytes.Length; i++) { // Display the physical address in hexadecimal. Output += bytes[i].ToString("X2"); // Insert a hyphen after each byte, unless we are at the end of the // address. if (i != bytes.Length) { Output += ":"; } } return Output.Trim(':'); }
public void SetOtherMac(PhysicalAddress mac) { lock (padlock) { theirMac = mac.GetAddressBytes(); } }
private string FormatMAC(PhysicalAddress a) { byte[] mac = a.GetAddressBytes(); return String.Join("-", (from b in mac select b.ToString("x2"))).ToUpper(); }
public static string GetHyphenatedHwAddress(PhysicalAddress hwAddress) { return BitConverter.ToString(hwAddress.GetAddressBytes()); }
/// <summary> /// Compares this MacAddress to a PhysicalAddress /// </summary> /// <param name="address">The PhysicalAddress to compare to</param> /// <returns>true if equal, otherwise false</returns> public bool CompareToPhysicalAddress(PhysicalAddress address) { try { return address != null && Bytes.SequenceEqual(address.GetAddressBytes()); } catch(NullReferenceException) { return false; } }
public static String PhysicalAddressToString(PhysicalAddress mac) { return BitConverter.ToString(mac.GetAddressBytes()).Replace('-',':'); }
/// <summary> /// Generates a node based on the bytes of the MAC address. /// </summary> /// <param name="mac"></param> /// <remarks>The machines MAC address can be retrieved from <see cref="NetworkInterface.GetPhysicalAddress"/>.</remarks> public static byte[] GenerateNodeBytes(PhysicalAddress mac) { if (mac == null) throw new ArgumentNullException("mac"); var node = mac.GetAddressBytes(); return node; }
/// <summary> /// Sendet ein Wake-On-LAN-Signal an einen Client. /// </summary> /// <param name="target">Der Ziel-IPEndPoint.</param> /// <param name="macAddress">Die MAC-Adresse des Clients.</param> ///<exception cref="System.ArgumentNullException">macAddress ist null.</exception> /// <returns>Ein asynchroner Task, welcher ein Wake-On-LAN-Signal an einen Client sendet.</returns> public static Task SendAsync(IPEndPoint target, PhysicalAddress macAddress) { if (target == null) throw new ArgumentNullException("target"); if (macAddress == null) throw new ArgumentNullException("macAddress"); var p = GetWolPacket(macAddress.GetAddressBytes()); return SendPacketAsync(target, p); //return new Task(() => Send(target, macAddress)); }
public override bool Pair(PhysicalAddress master) { var transfered = 0; var host = master.GetAddressBytes(); byte[] buffer = { 0x13, host[5], host[4], host[3], host[2], host[1], host[0], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Buffer.BlockCopy(GlobalConfiguration.Instance.BdLink, 0, buffer, 7, GlobalConfiguration.Instance.BdLink.Length); if (SendTransfer(UsbHidRequestType.HostToDevice, UsbHidRequest.SetReport, 0x0313, buffer, ref transfered)) { HostAddress = master; Log.DebugFormat("++ Paired DS4 [{0}] To BTH Dongle [{1}]", DeviceAddress.AsFriendlyName(), HostAddress.AsFriendlyName()); return true; } Log.DebugFormat("++ Pair Failed [{0}]", DeviceAddress.AsFriendlyName()); return false; }
/// <summary> /// Sendet ein Wake-On-LAN-Signal an einen Client. /// </summary> /// <param name="target">Der Ziel-IPEndPoint.</param> /// <param name="macAddress">Die MAC-Adresse des Clients.</param> /// <param name="password">Das SecureOn-Passwort des Clients.</param> /// <exception cref="System.ArgumentNullException">macAddress ist null.</exception> /// <exception cref="System.ArgumentNullException">password ist null.</exception> /// <returns>Ein asynchroner Task, welcher ein Wake-On-LAN-Signal an einen Client sendet.</returns> public static Task SendAsync(IPEndPoint target, PhysicalAddress macAddress, SecureOnPassword password) { if (target == null) throw new ArgumentNullException("target"); if (macAddress == null) throw new ArgumentNullException("macAddress"); if (password == null) throw new ArgumentNullException("password"); var passwordBuffer = password.GetPasswordBytes(); var p = GetWolPacket(macAddress.GetAddressBytes(), passwordBuffer); return SendPacketAsync(target, p); }
public static string FormatMAC(this PhysicalAddress mac) { return(string.Join(":", mac.GetAddressBytes().Select(b => $"{b:x2}"))); }
/*** bool BroadCast(PhysicalAddress macAddress) * * Parameters: * * rgMAC - The MAC address to broadcast as a Magic Packet * * Return Values: * TRUE is the broadcast succeeded, FALSE otherwise. * Since this is UDP, it probably succeeded. * * Errors: * * * Description: * * This creates a Magic Packet with the specified MAC address of * the machine to wake up and broadcasts it. * * A Magic Packet is 6 0xFF followed by 16 * copies of the MAC address. * ------------------------------------------------------------ */ private static bool BroadCast(PhysicalAddress macAddress) { int i = 0; byte[] rgDataGram = new byte[102]; // 6 0xFF and 16 * 6 byte MAC = 17 * 6 = 102 bytes UdpClient updClient = new UdpClient(); IPEndPoint ipBroadCast = new IPEndPoint(IPAddress.Broadcast, 0xFF); int cbSent = 0; // build the datagram // first there must be 6 bytes of 0xFF; for (i = 0; i < 6; i++) rgDataGram[i] = 0xFF; // then 16 MAC for (int j = 0; j < 16; j++) { macAddress.GetAddressBytes().CopyTo(rgDataGram, (j + 1) * 6); } updClient.EnableBroadcast = true; cbSent = updClient.Send(rgDataGram, rgDataGram.Length, ipBroadCast); if (cbSent == rgDataGram.Length) { Console.WriteLine("Magic Packet Sent."); return (true); } else { return (false); } }