/*** SenderWOLRequest(IPINFO ipInfo) * * Parameters: * * ipInfo - The global 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 client side RemoteWol code. * ------------------------------------------------------------ */ private static void SenderWOLRequest(IPINFO ipInfo) { TcpClient tcpClient = new TcpClient(); IPEndPoint ipEndPoint = new IPEndPoint(ipInfo.ip4, ipInfo.port); NetworkStream targetStrm = null; try { // connect to the server; there is some default timeout, it does break out if it can not connect. tcpClient.Connect(ipEndPoint); targetStrm = tcpClient.GetStream(); // send the MAC if (ipInfo.mac != null) { MSG msg = new MSG(); BHE bhe = new BHE(); msg.cmdmsg = MSG.CMDMSG.BroadCastMAC; msg.rgbData = ipInfo.mac.GetAddressBytes(); // ask that the magic packet be sent if (WriteMsgToStream(targetStrm, msg)) { msg = ReadMsgFromStream(targetStrm); } // See what we got back, it should only be the MAC we sent if (msg != null && msg.cmdmsg == MSG.CMDMSG.Succeeded) { Console.WriteLine("Magic Packet Sent."); } else { Console.WriteLine("Unable to send Magic Packet"); } } Console.WriteLine(""); // success or failure, close up the tcp Client targetStrm.Close(); tcpClient.Close(); } // we didn't even connect, probably the IP address is bad. catch (Exception e) { Console.WriteLine(e.ToString()); return; } }
/*** bool GetPort(string szPort, IPINFO ipd) * * Parameters: * * szPort - The port number represented as a string * ipd - This is the global data structure to save our server Port into * * Return Values: * true if we got a valid port number, false otherwise * * Errors: * * Description: * * Very simple, convert a string port number into a number port number * * ------------------------------------------------------------ */ private bool GetPort(string szPort, IPINFO ipd) { try { ipd.port = Convert.ToInt32(szPort); return(true); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); } // if we had an error, print out that this is not a good Port Console.WriteLine("Invalid Port: " + szPort); Console.WriteLine(""); return(false); }
private void publicIP_Load(object sender, EventArgs e) { myIP = IPINFO.Text; //-- your result string url = "http://checkip.dyndns.org"; System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); string response = sr.ReadToEnd().Trim(); string[] a = response.Split(':'); string a2 = a[1].Substring(1); string[] a3 = a2.Split('<'); string a4 = a3[0]; IPINFO.Text = a4; IPINFO.Refresh(); }
private void getip() { //Get your public IP myIP = IPINFO.Text; //-- your result string url = "http://checkip.dyndns.org"; System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); string response = sr.ReadToEnd().Trim(); string[] a = response.Split(':'); string a2 = a[1].Substring(1); string[] a3 = a2.Split('<'); string a4 = a3[0]; IPINFO.Text = a4; IPINFO.Refresh(); IPADDR.Visible = true; }
/*** bool GetMac(string szMAC, IPINFO ipd) * * Parameters: * * szMAC - The MAC number represented as a string * ipd - This is the global data structure to save our server MAC address into * * Return Values: * true if we got a valid MAC, false otherwise * * Errors: * * Description: * * Very simple, convert a string MAC number into a number MAC number * * ------------------------------------------------------------ */ private bool GetMac(string szMAC, IPINFO ipd) { // MAC Addresses are 6 bytes (12 characters) long, plus maybe 5 characters for : or - if (szMAC.Length == 12 || szMAC.Length == 17) { try { ipd.mac = PhysicalAddress.Parse((String.Copy(szMAC)).Replace(':', '-').ToUpper()).GetAddressBytes(); return(ipd.mac.Length == 6); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); Console.WriteLine("Invalid MAC Adress: " + szMAC); Console.WriteLine(""); } } return(false); }
/*** bool GetIPAddress(string szIP, IPINFO ipd) * * Parameters: * * szIP - The hostname to get the IP address for * ipd - This is the global data structure to save our server IP address into * * Return Values: * true if we could resolve the remote IP address, false if not * * Errors: * * Description: * * This resolves the hostname (szIP) to an binary IP address via DNS * It looks specifically for an IPv4 IP address as we do not support IPv6. * ------------------------------------------------------------ */ private bool GetIPAddress(string szIP, IPINFO ipd) { byte[] ipAddress = new byte[0]; try { // get the server to talk to IPAddress[] rgIPAddr = Dns.GetHostAddresses(szIP); // I have to find a IP4 address; don't support anything else foreach (IPAddress ipAddr in rgIPAddr) { if (ipAddr.AddressFamily == AddressFamily.InterNetwork) { ipAddress = ipAddr.GetAddressBytes(); if (ipAddress.Length == 4) { ipd.ip4 = ipAddress; } break; } } } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); } if (ipAddress.Length != 4) { Console.WriteLine("Invalid IP Address: " + szIP); Console.WriteLine(""); return(false); } else { return(true); } }
/*** PrintBroadcastHistor(IPINFO ipInfo) * * Parameters: * * ipInfo - The global 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 client side RemoteWol code. * ------------------------------------------------------------ */ private static void PrintBroadcastHistory(IPINFO ipInfo, DateTimeKind dtk) { TcpClient tcpClient = new TcpClient(); IPEndPoint ipEndPoint = new IPEndPoint(ipInfo.ip4, ipInfo.port); NetworkStream targetStrm = null; try { // connect to the server; there is some default timeout, it does break out if it can not connect. tcpClient.Connect(ipEndPoint); targetStrm = tcpClient.GetStream(); MSG msg = new MSG(MSG.CMDMSG.HistoryRequest); // ask that the magic packet be sent if (WriteMsgToStream(targetStrm, msg)) { msg = ReadMsgFromStream(targetStrm); } // See what we got back, it should be a history reply if (msg != null && msg.cmdmsg == MSG.CMDMSG.HistoryReply && msg.rgbData.Length % BHE.Length == 0) { byte[] rgbBHE = new byte[BHE.Length]; BHE bhe = null; Console.WriteLine("Got the broadcast history."); for (int i = 0; i < msg.rgbData.Length; i += BHE.Length) { // get a bhe Array.Copy(msg.rgbData, i, rgbBHE, 0, BHE.Length); bhe = new BHE(rgbBHE); switch (dtk) { case DateTimeKind.Utc: Console.WriteLine("UTC Time: {0}, MAC: {1} from IP: {2}.", bhe.UtcTime.ToString("G"), bhe.MAC.ToString(), bhe.IP.ToString()); break; case DateTimeKind.Local: Console.WriteLine("Local Time: {0}, MAC: {1} from IP: {2}.", bhe.UtcTime.ToLocalTime().ToString("G"), bhe.MAC.ToString(), bhe.IP.ToString()); break; } } } else { Console.WriteLine("Unable to get Broadcast History."); } Console.WriteLine(""); // success or failure, close up the tcp Client targetStrm.Close(); tcpClient.Close(); } // we didn't even connect, probably the IP address is bad. catch (Exception e) { Console.WriteLine(e.ToString()); return; } }
/*** void Main(string[] args) * * Parameters: * * args - command line strings * * * Return Values: * None * * Errors: * * * Description: * * Main entrypoint to the program. * * if only a port number, it is assumed to be a server side (listening) code * if only a MAC, then it is an immediate broadcast of the Magic Packet. * Otherwise as a client an IP address, Port number, and MAC value is expected. * See help screen info below. * ------------------------------------------------------------ */ static void Main(string[] args) { IPINFO ipInfo = new IPINFO(); bool fServer = false; bool fClient = false; bool fBroadCast = false; bool fGetHistory = false; DateTimeKind dtk = DateTimeKind.Utc; Thread thrdListen = new Thread(ListenForWOLRequest); Console.WriteLine("RemoteWol Version {0}", typeof(RemoteWol).Assembly.GetName().Version.ToString()); Console.WriteLine("Keith Vogel, Copyright 2011"); Console.WriteLine(""); // if we only have only 1 parameter, then we have either a port number and we are server // or we have a MAC and we are to send a Magic Packet broadcast to the MAC if (args.Length == 1) { // if this is a Mac Address, a valid port number would never be 6 bytes long. if (args[0].Length == 12 || args[0].Length == 17) { fBroadCast = (ipInfo.mac = GetMac(args[0])) != null; } else { fServer = ((ipInfo.port = GetPort(args[0])) != 0); } } // else if we have IP, Port, and MAC, we are sending a WOL request else if (args.Length == 3) { // Get the IP if ((ipInfo.ip4 = GetIPv4Address(args[0])) != null) { // now get the port if ((ipInfo.port = GetPort(args[1])) != 0) { // see if this is an option if (args[2].Length == 2 && (args[2][0] == '/' || args[2][0] == '-')) { switch (args[2][1]) { case 'h': fGetHistory = true; dtk = DateTimeKind.Local; break; case 'H': fGetHistory = true; dtk = DateTimeKind.Utc; break; default: break; } } // see if is to send a broadcast else if ((fClient = ((ipInfo.mac = GetMac(args[2])) != null))) { // if we want both server and client to run. fServer = (fRunServerAndClient && fClient); } } } } // if we are to run the server if (fServer) { // this starts a thread and will return immediately thrdListen.Start(ipInfo); // this is so we don't start the client too fast if the client is to be started as well. Thread.Sleep(5000); // give it sometime to start the server if (fClient) { SenderWOLRequest(ipInfo); } } // if we are to run the client else if (fClient) { SenderWOLRequest(ipInfo); } // if we are to broadcast the Magic Packet else if (fBroadCast) { // we only care about the MAC address BroadCast(ipInfo.mac); } else if (fGetHistory) { PrintBroadcastHistory(ipInfo, dtk); } // This is the Help Screen Info // if we are to do nothing, print help. else { Console.WriteLine("Server:\t\tRemoteWol Port"); Console.WriteLine("Client:\t\tRemoteWol ServerURL Port MAC"); Console.WriteLine("Remote Request:\tRemoteWol ServerURL Port -X"); Console.WriteLine("WOL Broadcast:\tRemoteWol MAC"); Console.WriteLine(""); Console.WriteLine("Where:"); Console.WriteLine(""); Console.WriteLine(" ServerURL:\tis the IP/DNS Name of the server to transmit the WOL."); Console.WriteLine(" Port:\tis the decimal port number the server is listening on."); Console.WriteLine(" MAC:\tis the 12 hex character MAC Address of the machine to wake up,"); Console.WriteLine(" \t\t colons \":\" and dashes \"-\" are allowed between hex bytes."); Console.WriteLine(" X:"); Console.WriteLine(" \t h:\tRequest broadcast history displayed in local time."); Console.WriteLine(" \t H:\tRequest broadcast history displayed in UTC time."); Console.WriteLine(""); Console.WriteLine("Example:"); Console.WriteLine(""); Console.WriteLine(" RemoteWol mynetwork.com 2000 65:24:EF:04:23:FC"); } return; }
/*** bool GetMac(string szMAC, IPINFO ipd) * * Parameters: * * szMAC - The MAC number represented as a string * ipd - This is the global data structure to save our server MAC address into * * Return Values: * true if we got a valid MAC, false otherwise * * Errors: * * Description: * * Very simple, convert a string MAC number into a number MAC number * * ------------------------------------------------------------ */ private bool GetMac(string szMAC, IPINFO ipd) { // MAC Addresses are 6 bytes (12 characters) long, plus maybe 5 characters for : or - if (szMAC.Length == 12 || szMAC.Length == 17) { try { ipd.mac = PhysicalAddress.Parse((String.Copy(szMAC)).Replace(':', '-').ToUpper()).GetAddressBytes(); return (ipd.mac.Length == 6); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); Console.WriteLine("Invalid MAC Adress: " + szMAC); Console.WriteLine(""); } } return (false); }
/*** bool GetPort(string szPort, IPINFO ipd) * * Parameters: * * szPort - The port number represented as a string * ipd - This is the global data structure to save our server Port into * * Return Values: * true if we got a valid port number, false otherwise * * Errors: * * Description: * * Very simple, convert a string port number into a number port number * * ------------------------------------------------------------ */ private bool GetPort(string szPort, IPINFO ipd) { try { ipd.port = Convert.ToInt32(szPort); return (true); } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); } // if we had an error, print out that this is not a good Port Console.WriteLine("Invalid Port: " + szPort); Console.WriteLine(""); return (false); }
/*** bool GetIPAddress(string szIP, IPINFO ipd) * * Parameters: * * szIP - The hostname to get the IP address for * ipd - This is the global data structure to save our server IP address into * * Return Values: * true if we could resolve the remote IP address, false if not * * Errors: * * Description: * * This resolves the hostname (szIP) to an binary IP address via DNS * It looks specifically for an IPv4 IP address as we do not support IPv6. * ------------------------------------------------------------ */ private bool GetIPAddress(string szIP, IPINFO ipd) { byte[] ipAddress = new byte[0]; try { // get the server to talk to IPAddress[] rgIPAddr = Dns.GetHostAddresses(szIP); // I have to find a IP4 address; don't support anything else foreach (IPAddress ipAddr in rgIPAddr) { if (ipAddr.AddressFamily == AddressFamily.InterNetwork) { ipAddress = ipAddr.GetAddressBytes(); if (ipAddress.Length == 4) { ipd.ip4 = ipAddress; } break; } } } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); Console.WriteLine(""); } if (ipAddress.Length != 4) { Console.WriteLine("Invalid IP Address: " + szIP); Console.WriteLine(""); return (false); } else { return (true); } }
/*** PrintBroadcastHistor(IPINFO ipInfo) * * Parameters: * * ipInfo - The global 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 client side RemoteWol code. * ------------------------------------------------------------ */ private static void PrintBroadcastHistory(IPINFO ipInfo, DateTimeKind dtk) { TcpClient tcpClient = new TcpClient(); IPEndPoint ipEndPoint = new IPEndPoint(ipInfo.ip4, ipInfo.port); NetworkStream targetStrm = null; try { // connect to the server; there is some default timeout, it does break out if it can not connect. tcpClient.Connect(ipEndPoint); targetStrm = tcpClient.GetStream(); MSG msg = new MSG(MSG.CMDMSG.HistoryRequest); // ask that the magic packet be sent if (WriteMsgToStream(targetStrm, msg)) { msg = ReadMsgFromStream(targetStrm); } // See what we got back, it should be a history reply if (msg != null && msg.cmdmsg == MSG.CMDMSG.HistoryReply && msg.rgbData.Length % BHE.Length == 0) { byte[] rgbBHE = new byte[BHE.Length]; BHE bhe = null; Console.WriteLine("Got the broadcast history."); for (int i = 0; i < msg.rgbData.Length; i += BHE.Length) { // get a bhe Array.Copy(msg.rgbData, i, rgbBHE, 0, BHE.Length); bhe = new BHE(rgbBHE); switch(dtk) { case DateTimeKind.Utc: Console.WriteLine("UTC Time: {0}, MAC: {1} from IP: {2}.", bhe.UtcTime.ToString("G"), bhe.MAC.ToString(), bhe.IP.ToString()); break; case DateTimeKind.Local: Console.WriteLine("Local Time: {0}, MAC: {1} from IP: {2}.", bhe.UtcTime.ToLocalTime().ToString("G"), bhe.MAC.ToString(), bhe.IP.ToString()); break; } } } else { Console.WriteLine("Unable to get Broadcast History."); } Console.WriteLine(""); // success or failure, close up the tcp Client targetStrm.Close(); tcpClient.Close(); } // we didn't even connect, probably the IP address is bad. catch (Exception e) { Console.WriteLine(e.ToString()); return; } }
/*** 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(); }
/*** SenderWOLRequest(IPINFO ipInfo) * * Parameters: * * ipInfo - The global 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 client side RemoteWol code. * ------------------------------------------------------------ */ private void SenderWOLRequest(IPINFO ipInfo) { TcpClient tcpClient = new TcpClient(); IPAddress ipAddrTarget = new IPAddress(ipInfo.ip4); IPEndPoint ipEndPoint = new IPEndPoint(ipAddrTarget, ipInfo.port); NetworkStream targetStrm = null; bool fFoundMac = false; byte[] rgRcv = new byte[1024]; int cbRead = 0; try { // connect to the server; there is some default timeout, it does break out if it can not connect. tcpClient.Connect(ipEndPoint); targetStrm = tcpClient.GetStream(); // send the MAC if (ipInfo.mac != null) { Debug.Assert(ipInfo.mac.Length == 6); try { // write out the MAC address targetStrm.WriteTimeout = 30000; // set to 30 seconds for the write targetStrm.Write(ipInfo.mac, 0, ipInfo.mac.Length); // now the MAC and only the MAC should come back targetStrm.ReadTimeout = 30000; // set to 30 seconds for the read cbRead = targetStrm.Read(rgRcv, 0, rgRcv.Length); } // just want to catch errors and get out. // this could be caused by the timeout catch (Exception e) { Console.WriteLine(e.ToString()); } // See what we got back, it should only be the MAC we sent // This is not intended to be secure, it is only a sanity check // so that we know we probably sent it to a RemoteWOL server // instead of some random server that sent us goo back. if ((fFoundMac = (cbRead == ipInfo.mac.Length))) { for (int i = 0; i < ipInfo.mac.Length; i++) { fFoundMac = fFoundMac && rgRcv[i] == ipInfo.mac[i]; } } if (fFoundMac) { Console.WriteLine("Magic Packet Sent"); } else { Console.WriteLine("Unable to send Magic Packet"); } } #if QUIT // send the exit code // this only make sense if we are supporting remote exit. else { targetStrm.Write(rgTerm, 0, rgTerm.Length); cbRead = targetStrm.Read(rgRcv, 0, rgRcv.Length); if (cbRead == rgTerm.Length) { Console.WriteLine("Server terminated"); } else { Console.WriteLine("Unable terminate server"); } } #endif Console.WriteLine(""); // success or failure, close up the tcp Client targetStrm.Close(); tcpClient.Close(); } // we didn't even connect, probably the IP address is bad. catch (Exception e) { Console.WriteLine(e.ToString()); return; } }
/*** void Main(string[] args) * * Parameters: * * args - command line strings * * * Return Values: * None * * Errors: * * * Description: * * Main entrypoint to the program. * * if only a port number, it is assumed to be a server side (listening) code * if only a MAC, then it is an immediate broadcast of the Magic Packet. * Otherwise as a client an IP address, Port number, and MAC value is expected. * See help screen info below. * ------------------------------------------------------------ */ static void Main(string[] args) { IPINFO ipInfo = new IPINFO(); bool fServer = false; bool fClient = false; bool fBroadCast = false; bool fQuit = false; RemoteWol remoteWol = new RemoteWol(); Thread thrdListen = new Thread(remoteWol.ListenForWOLRequest); Console.WriteLine("RemoteWol Version {0}", typeof(RemoteWol).Assembly.GetName().Version.ToString()); Console.WriteLine("Keith Vogel, Copywrite 2011"); Console.WriteLine(""); // if we only have only 1 parameter, then we have either a port number and we are server // or we have a MAC and we are to send a Magic Packet broadcast to the MAC if (args.Length == 1) { // if this is a Mac Address, a valid port number would never be 6 bytes long. if (args[0].Length == 12 || args[0].Length == 17) { fBroadCast = remoteWol.GetMac(args[0], ipInfo);; } else { fServer = remoteWol.GetPort(args[0], ipInfo); } } #if QUIT // else if we have IP and Port but no MAC, this means to terminate the server side. else if (args.Length == 2) { // Get the IP if (remoteWol.GetIPAddress(args[0], ipInfo)) { // now get the port fQuit = remoteWol.GetPort(args[1], ipInfo); } } #endif // else if we have IP, Port, and MAC, we are sending a WOL request else if (args.Length == 3) { // Get the IP if (remoteWol.GetIPAddress(args[0], ipInfo)) { // now get the port if (remoteWol.GetPort(args[1], ipInfo)) { // and finally get the MAC fClient = remoteWol.GetMac(args[2], ipInfo); // if we want both server and client to run. fServer = (fRunServerAndClient && fClient); } } } // if we are to run the server if (fServer) { // this starts a thread and will return immediately thrdListen.Start(ipInfo); // this is so we don't start the client too fast if the client is to be started as well. Thread.Sleep(5000); // give it sometime to start the server } // if we are to run the client if (fClient || fQuit) { remoteWol.SenderWOLRequest(ipInfo); } // if we are to broadcast the Magic Packet if (fBroadCast) { if (remoteWol.BroadCast(ipInfo.mac)) { Console.WriteLine("Magic Packet Sent"); } else { Console.WriteLine("Unable to send Magic Packet"); } } // This is the Help Screen Info // if we are to do nothing, print help. if (!fServer && !fClient && !fBroadCast && !fQuit) { Console.WriteLine("Server:\t\tRemoteWol Port"); Console.WriteLine("Client:\t\tRemoteWol ServerURL Port MAC"); Console.WriteLine("WOL Broadcast:\tRemoteWol MAC"); #if QUIT Console.WriteLine("Quit Server:\tRemoteWol ServerURL Port"); #endif Console.WriteLine(""); Console.WriteLine("Where:"); Console.WriteLine(""); Console.WriteLine(" ServerURL:\tis the IP/DNS Name of the server to transmit the WOL."); Console.WriteLine(" Port:\tis the decimal port number the server is listening on."); Console.WriteLine(" MAC:\tis the 12 hex character MAC Address of the machine to wake up,"); Console.WriteLine(" \t\t colons \":\" and dashes \"-\" are allowed between hex bytes."); Console.WriteLine(""); Console.WriteLine("Example:"); Console.WriteLine(""); Console.WriteLine(" RemoteWol mynetwork.com 2000 65:24:EF:04:23:FC"); return; } }
/*** 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(); }
/*** void Main(string[] args) * * Parameters: * * args - command line strings * * * Return Values: * None * * Errors: * * * Description: * * Main entrypoint to the program. * * if only a port number, it is assumed to be a server side (listening) code * if only a MAC, then it is an immediate broadcast of the Magic Packet. * Otherwise as a client an IP address, Port number, and MAC value is expected. * See help screen info below. * ------------------------------------------------------------ */ static void Main(string[] args) { IPINFO ipInfo = new IPINFO(); bool fServer = false; bool fClient = false; bool fBroadCast = false; bool fQuit = false; RemoteWol remoteWol = new RemoteWol(); Thread thrdListen = new Thread(remoteWol.ListenForWOLRequest); Console.WriteLine("RemoteWol Version {0}", typeof(RemoteWol).Assembly.GetName().Version.ToString()); Console.WriteLine("Keith Vogel, Copywrite 2011"); Console.WriteLine(""); // if we only have only 1 parameter, then we have either a port number and we are server // or we have a MAC and we are to send a Magic Packet broadcast to the MAC if (args.Length == 1) { // if this is a Mac Address, a valid port number would never be 6 bytes long. if (args[0].Length == 12 || args[0].Length == 17) { fBroadCast = remoteWol.GetMac(args[0], ipInfo); ; } else { fServer = remoteWol.GetPort(args[0], ipInfo); } } #if QUIT // else if we have IP and Port but no MAC, this means to terminate the server side. else if (args.Length == 2) { // Get the IP if (remoteWol.GetIPAddress(args[0], ipInfo)) { // now get the port fQuit = remoteWol.GetPort(args[1], ipInfo); } } #endif // else if we have IP, Port, and MAC, we are sending a WOL request else if (args.Length == 3) { // Get the IP if (remoteWol.GetIPAddress(args[0], ipInfo)) { // now get the port if (remoteWol.GetPort(args[1], ipInfo)) { // and finally get the MAC fClient = remoteWol.GetMac(args[2], ipInfo); // if we want both server and client to run. fServer = (fRunServerAndClient && fClient); } } } // if we are to run the server if (fServer) { // this starts a thread and will return immediately thrdListen.Start(ipInfo); // this is so we don't start the client too fast if the client is to be started as well. Thread.Sleep(5000); // give it sometime to start the server } // if we are to run the client if (fClient || fQuit) { remoteWol.SenderWOLRequest(ipInfo); } // if we are to broadcast the Magic Packet if (fBroadCast) { if (remoteWol.BroadCast(ipInfo.mac)) { Console.WriteLine("Magic Packet Sent"); } else { Console.WriteLine("Unable to send Magic Packet"); } } // This is the Help Screen Info // if we are to do nothing, print help. if (!fServer && !fClient && !fBroadCast && !fQuit) { Console.WriteLine("Server:\t\tRemoteWol Port"); Console.WriteLine("Client:\t\tRemoteWol ServerURL Port MAC"); Console.WriteLine("WOL Broadcast:\tRemoteWol MAC"); #if QUIT Console.WriteLine("Quit Server:\tRemoteWol ServerURL Port"); #endif Console.WriteLine(""); Console.WriteLine("Where:"); Console.WriteLine(""); Console.WriteLine(" ServerURL:\tis the IP/DNS Name of the server to transmit the WOL."); Console.WriteLine(" Port:\tis the decimal port number the server is listening on."); Console.WriteLine(" MAC:\tis the 12 hex character MAC Address of the machine to wake up,"); Console.WriteLine(" \t\t colons \":\" and dashes \"-\" are allowed between hex bytes."); Console.WriteLine(""); Console.WriteLine("Example:"); Console.WriteLine(""); Console.WriteLine(" RemoteWol mynetwork.com 2000 65:24:EF:04:23:FC"); return; } }
/*** SenderWOLRequest(IPINFO ipInfo) * * Parameters: * * ipInfo - The global 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 client side RemoteWol code. * ------------------------------------------------------------ */ private void SenderWOLRequest(IPINFO ipInfo) { TcpClient tcpClient = new TcpClient(); IPAddress ipAddrTarget = new IPAddress(ipInfo.ip4); IPEndPoint ipEndPoint = new IPEndPoint(ipAddrTarget, ipInfo.port); NetworkStream targetStrm = null; bool fFoundMac = false; byte[] rgRcv = new byte[1024]; int cbRead = 0; try { // connect to the server; there is some default timeout, it does break out if it can not connect. tcpClient.Connect(ipEndPoint); targetStrm = tcpClient.GetStream(); // send the MAC if (ipInfo.mac != null) { Debug.Assert(ipInfo.mac.Length == 6); try { // write out the MAC address targetStrm.WriteTimeout = 30000; // set to 30 seconds for the write targetStrm.Write(ipInfo.mac, 0, ipInfo.mac.Length); // now the MAC and only the MAC should come back targetStrm.ReadTimeout = 30000; // set to 30 seconds for the read cbRead = targetStrm.Read(rgRcv, 0, rgRcv.Length); } // just want to catch errors and get out. // this could be caused by the timeout catch (Exception e) { Console.WriteLine(e.ToString()); } // See what we got back, it should only be the MAC we sent // This is not intended to be secure, it is only a sanity check // so that we know we probably sent it to a RemoteWOL server // instead of some random server that sent us goo back. if ((fFoundMac = (cbRead == ipInfo.mac.Length))) { for(int i = 0; i < ipInfo.mac.Length; i++) { fFoundMac = fFoundMac && rgRcv[i] == ipInfo.mac[i]; } } if (fFoundMac) { Console.WriteLine("Magic Packet Sent"); } else { Console.WriteLine("Unable to send Magic Packet"); } } #if QUIT // send the exit code // this only make sense if we are supporting remote exit. else { targetStrm.Write(rgTerm, 0, rgTerm.Length); cbRead = targetStrm.Read(rgRcv, 0, rgRcv.Length); if (cbRead == rgTerm.Length) { Console.WriteLine("Server terminated"); } else { Console.WriteLine("Unable terminate server"); } } #endif Console.WriteLine(""); // success or failure, close up the tcp Client targetStrm.Close(); tcpClient.Close(); } // we didn't even connect, probably the IP address is bad. catch (Exception e) { Console.WriteLine(e.ToString()); return; } }