本文整理汇总了C#中System.Net.NetworkInformation.PhysicalAddress.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# PhysicalAddress.ToString方法的具体用法?C# PhysicalAddress.ToString怎么用?C# PhysicalAddress.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.NetworkInformation.PhysicalAddress
的用法示例。
在下文中一共展示了PhysicalAddress.ToString方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddUserIfNecessary
public void AddUserIfNecessary(string DoesExist, PhysicalAddress passed_mac_address,string filepath)
{
if (DoesExist == "Does not exist")
{
File.AppendAllText(filepath, passed_mac_address.ToString() + ' ' + "Unknown" + ' ' + "Unknown" + Environment.NewLine);
User user = new User();
user.id = id;
user.mac_address = passed_mac_address;
user.name = "Unknown";
user.status = "Connected";
user.gender = "Unknown";
users.Add(user);
id++;
//TODO: Greetings, stranger!
Console.WriteLine("Greetings stranger! :"+passed_mac_address.ToString());
}
}
示例2: CheckIfUserIsConnectedAndExists
public string CheckIfUserIsConnectedAndExists(PhysicalAddress passed_mac_address)
{
foreach (User user in users)
{
if (user.mac_address.ToString() == passed_mac_address.ToString())
{
if (user.status == "Disconnected")
{
user.status = "Connected";
//TODO: Greetings!
Console.WriteLine("Greetings! You are NOW connected! :" + passed_mac_address.ToString());
return "Exists";
}
else
if(user.status == "Connected")
{
Console.WriteLine("Greetings! You are already connected! :"+passed_mac_address.ToString());
return "Exists";
}
}
}
return "Does not exist";
}
示例3: FriendlyPhysicalAddress
// convert MAC to friendly MAC (with :)
public static string FriendlyPhysicalAddress(PhysicalAddress mac)
{
var macString = mac.ToString();
var output = string.Empty;
for (int i = 0; i < macString.Length; i++)
{
if (i % 2 == 0 && i > 0)
{
output += ":" + macString[i];
}
else
{
output += macString[i];
}
}
return output;
}
示例4: ToStringTest
public void ToStringTest()
{
PhysicalAddress phys1 = new PhysicalAddress(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 });
Assert.AreEqual("010203040506", phys1.ToString());
}
示例5: RestartInterface
/// <summary>
/// Assign a random MAC address to the current interface and restart both the network
/// interface and the login console
/// </summary>
private void RestartInterface()
{
// random mac address
var bytes = new byte[6];
_random.NextBytes(bytes);
bytes[0] = 0x02; // win7 work around
var physicalAddress = new PhysicalAddress(bytes.ToArray());
if (_notifyIcon != null && _notifyIcon.Text.Length != 0 && _notifyIcon.Text.IndexOf(Environment.NewLine) > 0) {
var usage = _notifyIcon.Text.Substring(_notifyIcon.Text.IndexOf(Environment.NewLine) + Environment.NewLine.Length);
_internetAccess.AddProgress("Restarting interface, usage was '" + usage + "'");
}
try {
_selectedNetworkInterface.PhysicalAddress = physicalAddress.ToString();
_selectedNetworkInterface.RestartInterface();
} catch (System.Security.SecurityException) {
if (_notifyIcon != null) {
_notifyIcon.BalloonTipText = "Interface restart failed, no administrator privs?";
_notifyIcon.ShowBalloonTip(250);
}
return;
}
// it worked?
if (_notifyIcon != null) {
_notifyIcon.BalloonTipText = "Restarted " + _selectedNetworkInterface.Name;
_notifyIcon.ShowBalloonTip(250);
}
// restart graph as well
// RestartGraph();
// log back in to restore internet access
Login();
}
示例6: Resolve
/// <summary>
/// Resolves the MAC address of the specified IP address
/// </summary>
/// <param name="destIP">The IP address to resolve</param>
/// <param name="localIP">The local IP address from which to send the ARP request, if null the local address will be discovered</param>
/// <param name="localMAC">The localMAC address to use, if null the local mac will be discovered</param>
/// <returns>The MAC address that matches to the given IP address or
/// null if there was a timeout</returns>
public PhysicalAddress Resolve(System.Net.IPAddress destIP,
System.Net.IPAddress localIP,
PhysicalAddress localMAC) {
// if no local ip address is specified attempt to find one from the adapter
if (localIP == null) {
if (_device.Addresses.Count > 0) {
// attempt to find an ipv4 address.
// ARP is ipv4, NDP is used for ipv6
foreach (var address in _device.Addresses) {
if (address.Addr.type == LibPcap.Sockaddr.AddressTypes.AF_INET_AF_INET6) {
// make sure the address is ipv4
if (address.Addr.ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
localIP = address.Addr.ipAddress;
break; // break out of the foreach
}
}
}
// if we can't find either an ipv6 or an ipv4 address use the localhost address
if (localIP == null) {
localIP = System.Net.IPAddress.Parse("127.0.0.1");
}
}
}
// if no local mac address is specified attempt to find one from the device
if (localMAC == null) {
foreach (var address in _device.Addresses) {
if (address.Addr.type == LibPcap.Sockaddr.AddressTypes.HARDWARE) {
localMAC = address.Addr.hardwareAddress;
}
}
}
if (localIP == null) {
throw new System.InvalidOperationException("Unable to find local ip address");
}
if (localMAC == null) {
throw new System.InvalidOperationException("Unable to find local mac address");
}
//Build a new ARP request packet
var request = BuildRequest(destIP, localMAC, localIP);
//create a "tcpdump" filter for allowing only arp replies to be read
String arpFilter = "arp and ether dst " + localMAC.ToString();
//open the device with 20ms timeout
_device.Open(DeviceMode.Promiscuous, 20);
//set the filter
_device.Filter = arpFilter;
// set a last request time that will trigger sending the
// arp request immediately
var lastRequestTime = DateTime.FromBinary(0);
var requestInterval = new TimeSpan(0, 0, 1);
GodLesZ.Library.Network.Packet.ARPPacket arpPacket = null;
// attempt to resolve the address with the current timeout
var timeoutDateTime = DateTime.Now + Timeout;
while (DateTime.Now < timeoutDateTime) {
if (requestInterval < (DateTime.Now - lastRequestTime)) {
// inject the packet to the wire
_device.SendPacket(request);
lastRequestTime = DateTime.Now;
}
//read the next packet from the network
var reply = _device.GetNextPacket();
if (reply == null) {
continue;
}
// parse the packet
var packet = GodLesZ.Library.Network.Packet.Packet.ParsePacket(reply.LinkLayerType, reply.Data);
// is this an arp packet?
arpPacket = GodLesZ.Library.Network.Packet.ARPPacket.GetEncapsulated(packet);
if (arpPacket == null) {
continue;
}
//if this is the reply we're looking for, stop
if (arpPacket.SenderProtocolAddress.Equals(destIP)) {
break;
}
}
//.........这里部分代码省略.........
示例7: scanner_OnResponse
// scanner response - new target
private void scanner_OnResponse(string ip, bool ipv6, PhysicalAddress mac, string hostname, List<string> ipv6List = null)
{
Window.Dispatcher.Invoke(new UI(delegate
{
// check for existing MAC and update current item
var items = Window.TargetList.Where(o => o.MAC.Replace(":", "") == mac.ToString());
if (items.Count() > 0)
{
var item = items.First();
if (ipv6)
{
item.IPv6 = ip;
// change ipv6List
if (ipv6List != null && ipv6List.Count > 0) item.IPv6List = ipv6List;
// add ip to the list after ping response (ipv6List is null)
if (ipv6List == null && !item.IPv6List.Contains(ip)) item.IPv6List.Add(ip);
}
else
{
item.IP = ip;
}
}
// add new item
else
{
var item = new Target { Hostname = hostname, MAC = Network.FriendlyPhysicalAddress(mac), PMAC = mac, Vendor = GetVendorFromMAC(mac.ToString()) };
if (ipv6)
{
item.IPv6 = ip;
// change ipv6List
if (ipv6List != null && ipv6List.Count > 0) item.IPv6List = ipv6List;
// add ip to the list after ping response (ipv6List is null)
if (ipv6List == null && !item.IPv6List.Contains(ip)) item.IPv6List.Add(ip);
}
else
{
item.IP = ip;
}
// exclude local MAC
if (mac.ToString() != DeviceInfo.PMAC.ToString())
{
Window.TargetList.Add(item);
Window.TargetList.Sort();
}
}
}));
}
示例8: ListenForWOLRequest
/*** void ListenForWOLRequest(Object obj)
*
* Parameters:
*
* obj - The obj is really an ipInfo and is casted to such.
* The ipInfo class containing all of the IP like info about the
* this machine we are running on; and the server we want to contact.
*
* Return Values:
* None
*
* Errors:
*
*
* Description:
*
* This is the start of the server side RemoteWol code.
*
* This was written as a seperate thread so that debugging of
* the client in the main thread against a server in a different
* thread could be done in one debug session. Client / Server
* combined application is only when the debug flag fRunServerAndClient is TRUE.
* ------------------------------------------------------------ */
private void ListenForWOLRequest(Object obj)
{
IPINFO ipInfo = (IPINFO) obj;
byte[] rgRcv = new byte[2 * cbMACAddress];
uint terminate = 0;
TcpListener tcpListener = null;
try
{
// this will throw and exception if ipAddress == null;
tcpListener = new TcpListener(ipInfo.myIPs.ipMe, ipInfo.port);
tcpListener.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
// go in a loop waiting for someone to connect.
do
{
int cbRead = 0;
bool fEcho = false;
TcpClient client = null;
NetworkStream targetStrm = null;
try
{
// block until we get something
client = tcpListener.AcceptTcpClient();
targetStrm = client.GetStream();
// read the buffer
targetStrm.ReadTimeout = 10000; // set to 10 seconds for the read
// wait for something to come in
cbRead = targetStrm.Read(rgRcv, 0, rgRcv.Length);
// if it is a MAC address, then broadcast it.
if (cbRead == cbMACAddress)
{
// do the broadcast
fEcho = BroadCast(rgRcv);
}
#if QUIT
// if this is potentially a terminate
else if (cbRead == rgTerm.Length)
{
IPEndPoint ipEndPointClient = (IPEndPoint)client.Client.RemoteEndPoint;
if(ipInfo.myIPs.ipMe.Equals(ipEndPointClient.Address))
{
terminate = (uint)((rgRcv[0] << 24) | (rgRcv[1] << 16) | (rgRcv[2] << 8) | rgRcv[3]);
fEcho = (terminate == 0xFFFFFFFF);
}
}
#endif
// okay send something back.
if (fEcho)
{
// if we got something valid, echo it back as an ack
targetStrm.Write(rgRcv, 0, cbRead);
fEcho = false;
// print out the time and mac address
Array.Resize(ref rgRcv, 6);
PhysicalAddress macAddress = new PhysicalAddress(rgRcv);
Console.WriteLine(DateTime.Now.ToString("g") + " : " + macAddress.ToString());
}
else
{
// if not, then just return 1 byte to keep things from timing out on the client
targetStrm.Write(rgTerm, 0, 1);
//.........这里部分代码省略.........
示例9: GetManufacturerForHardwareAddress
/// <summary>
/// Searches for a match for the given mac address in the oui.txt file.
/// If a match is found, the corresponding company name is returned.
/// If a match is not found, null is returned.
/// If an error occurs, null is returned, and the exception is set.
///
/// Note: The oui list may contain missing names, so an empty string may be returned.
/// </summary>
private String GetManufacturerForHardwareAddress(PhysicalAddress macAddr, out Exception e)
{
if (macAddr == null)
{
e = new ArgumentNullException();
return null;
}
String macAddrPrefix = macAddr.ToString().Substring(0, 6);
StreamReader streamReader = null;
String result = null;
try
{
// OUI - Organizationally Unique Identifier
//
// If you wish to update the list of OUI's, you can get the latest version here:
// http://standards.ieee.org/regauth/oui/index.shtml
// Then format the list using the ReformatOUI method below.
// Ensure that the oui file is in UTF-8.
streamReader = File.OpenText("oui.txt");
String line = streamReader.ReadLine();
while ((line != null) && (result == null))
{
if (line.StartsWith(macAddrPrefix))
{
result = line.Substring(6).Trim();
}
line = streamReader.ReadLine();
}
}
catch (Exception ex)
{
e = ex;
}
finally
{
if(streamReader != null) streamReader.Close();
}
e = null;
return result;
}
示例10: ListenForWOLRequest
/*** void ListenForWOLRequest(Object obj)
*
* Parameters:
*
* obj - The obj is really an ipInfo and is casted to such.
* The ipInfo class containing all of the IP like info about the
* this machine we are running on; and the server we want to contact.
*
* Return Values:
* None
*
* Errors:
*
*
* Description:
*
* This is the start of the server side RemoteWol code.
*
* This was written as a seperate thread so that debugging of
* the client in the main thread against a server in a different
* thread could be done in one debug session. Client / Server
* combined application is only when the debug flag fRunServerAndClient is TRUE.
* ------------------------------------------------------------ */
private static void ListenForWOLRequest(Object obj)
{
IPINFO ipInfo = (IPINFO) obj;
uint terminate = 0;
TcpListener tcpListener = null;
try
{
// this will throw and exception if ipAddress == null;
tcpListener = new TcpListener(ipInfo.myIPs.ipMe, ipInfo.port);
tcpListener.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
// go in a loop waiting for someone to connect.
do
{
TcpClient client = null;
NetworkStream targetStrm = null;
MSG msg; ;
try
{
// block until we get something
Console.WriteLine("Listening on port: {0}.", ipInfo.port.ToString());
client = tcpListener.AcceptTcpClient();
targetStrm = client.GetStream();
// see if we can read something reasonable
msg = ReadMsgFromStream(targetStrm);
if (msg != null)
{
Console.WriteLine("{0}: Message {1} detected.", DateTime.Now.ToString("g"), msg.cmdmsg.ToString());
switch (msg.cmdmsg)
{
case MSG.CMDMSG.BroadCastMAC:
// see if we have a valid MAC
if (msg.rgbData.Length >= 6)
{
MSG msgRet = new MSG(MSG.CMDMSG.Failed);
BHE bhe = new BHE();
// we only care about the MAC address
Array.Resize(ref msg.rgbData, 6);
PhysicalAddress macAddress = new PhysicalAddress(msg.rgbData);
IPEndPoint ipEP = (IPEndPoint) client.Client.RemoteEndPoint;
Console.WriteLine("Request to broadcast MAC: {0} by IP: {1}.", macAddress.ToString(), ipEP.ToString());
bhe.IP = ipEP.Address;
bhe.MAC = macAddress;
bhe.UtcTime = DateTime.Now.ToUniversalTime();
ipInfo.bhs.AddBHE(bhe);
// do the broadcast
msg.cmdmsg = MSG.CMDMSG.Failed;
if (BroadCast(macAddress))
{
msgRet.cmdmsg = MSG.CMDMSG.Succeeded;
}
// write back our status code
WriteMsgToStream(targetStrm, msgRet);
}
break;
case MSG.CMDMSG.HistoryRequest:
WriteMsgToStream(targetStrm, ipInfo.bhs.GetBroadcastHistoryReplyMsg());
//.........这里部分代码省略.........