Exemplo n.º 1
0
        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());

            }
        }
Exemplo n.º 2
0
        private string Show_Mac_Address()
        {
            string MacAddress = "";

            // 현재 연결된 네트워크 장비의 정보를 들고 옴
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface adapter in adapters)
            {
                System.Net.NetworkInformation.PhysicalAddress pa = adapter.GetPhysicalAddress();

                if (pa != null && !pa.ToString().Equals(""))
                {
                    MacAddress = pa.ToString(); // 맥 어드레스 출력 해 줌
                    break;
                }
            }
            return(MacAddress);
        }
Exemplo n.º 3
0
        private static string formatMac(System.Net.NetworkInformation.PhysicalAddress resolvedMacAddress)
        {
            string          m     = resolvedMacAddress.ToString();
            MatchCollection split = Regex.Matches(m, @"\w{2}");
            string          mac   = "";

            foreach (Match item in split)
            {
                mac += item.Value + ":";
            }

            return(mac.Remove(mac.Length - 1));
        }
Exemplo n.º 4
0
 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";
 }
Exemplo n.º 5
0
        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());
        }
Exemplo n.º 6
0
        // 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;
        }
Exemplo n.º 7
0
		public void ToStringTest()
		{
			PhysicalAddress phys1 = new PhysicalAddress(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 });
			Assert.AreEqual("010203040506", phys1.ToString());
		}
Exemplo n.º 8
0
        /// <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();
        }
Exemplo n.º 9
0
		/// <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;
				}
			}

			// free the device
			_device.Close();

			// the timeout happened
			if (DateTime.Now >= timeoutDateTime) {
				return null;
			} else {
				//return the resolved MAC address
				return arpPacket.SenderHardwareAddress;
			}
		}
Exemplo n.º 10
0
        // 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();
                    }
                }
            }));
        }
Exemplo n.º 11
0
        /***	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);
                        fEcho = false;
                    }

                    // we have done our work, close the stream
                    targetStrm.Close();
                    client.Close();
                }

                // something bad happened, but we want to just print the exception and go back and wait
                // for another connection.
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    terminate = 0;
                }

            } while (terminate != 0xFFFFFFFF);

            // just stop listening, we are done.
            tcpListener.Stop();
        }
Exemplo n.º 12
0
        public Form1()
        {
            InitializeComponent();



            //========== IPv4 (Internal IP) ==========
            string      localIP = "Not available, please check your network seetings!";
            IPHostEntry host    = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP            = ip.ToString();
                    this.textBox1.Text = ip.ToString();
                }
            }
            //========== IPv4 (Internal IP) ==========


            //========== External IP ==========
            string externalip = new WebClient().DownloadString("http://ipinfo.io/ip").Trim(); //http://icanhazip.com

            if (String.IsNullOrWhiteSpace(externalip))
            {
                externalip = null;//null경우 Get Internal IP를 가져오게 한다.
            }
            this.textBox2.Text = externalip;
            //return externalip;
            //========== External IP ==========


            //========== MAC ===========
            string MacAddress = "";

            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                System.Net.NetworkInformation.PhysicalAddress pa = adapter.GetPhysicalAddress();
                if (pa != null && !pa.ToString().Equals(""))
                {
                    MacAddress = pa.ToString();
                    break;
                }
            }
            //return MacAddress;
            this.textBox3.Text = MacAddress;
            //========== MAC ===========



            //========== User name ==========
            var input = WindowsIdentity.GetCurrent().Name;

            string[] tab    = input.Split('\\');
            var      result = tab[1];          //var result = tab[1] + "@" + tab[0];

            this.textBox4.Text = result;
            //========== User name ==========



            //========== Host name ==========
            String hostName = Dns.GetHostName();

            Console.WriteLine("Computer name :" + hostName);
            this.textBox5.Text = hostName;
            //========== Host name ==========
        }
Exemplo n.º 13
0
        /// <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;
        }
Exemplo n.º 14
0
        /***	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());
                                break;

                            case MSG.CMDMSG.HistoryReply:
                                WriteMsgToStream(targetStrm, new MSG(MSG.CMDMSG.Failed));
                                break;

                            case MSG.CMDMSG.Terminate:
                                WriteMsgToStream(targetStrm, new MSG(MSG.CMDMSG.Succeeded));
                                terminate = 0xFFFFFFFF;
                                break;

                            default:
                                break;
                        }
                    }

                    // we have done our work, close the stream
                    targetStrm.Close();
                    client.Close();
                }

                // something bad happened, but we want to just print the exception and go back and wait
                // for another connection.
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    terminate = 0;
                }

            } while (terminate != 0xFFFFFFFF);

            // just stop listening, we are done.
            tcpListener.Stop();
        }