Form_IpConfig.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Net.Sockets;
  11. using System.Net;
  12. namespace NetworkDiscovery
  13. {
  14. public partial class Form_IpConfig : Form
  15. {
  16. bool dhcp = true;
  17. internal bool isChanged = false;
  18. protected Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  19. public const int UDP_TX_PORT = 49049; // порт передачи сообщений
  20. public const int UDP_RX_PORT = 49049; // порт приема сообщений
  21. protected UdpClient listener;
  22. public static List<IPAddress> MyIpList;
  23. protected const int delayTime = 500;
  24. private const int timeout = 5000;
  25. private List<String> messages = new List<String>();
  26. public string DeviceIP { get; private set; }
  27. public string SerialNo { get; private set; }
  28. public Form_IpConfig(string deviceIP, string serNo)
  29. {
  30. InitializeComponent();
  31. DeviceIP = deviceIP;
  32. SerialNo = serNo;
  33. textBox1.Text = DeviceIP;
  34. checkBox1.Checked = true;
  35. Thread ask = new Thread(this.StartListener);
  36. ask.Start();
  37. }
  38. //Кнопка "Применить"
  39. private void apply_button_click(object sender, EventArgs e)
  40. {
  41. if (!textBox1.ForeColor.Equals(Color.Green) || !textBox2.ForeColor.Equals(Color.Green) || !textBox3.ForeColor.Equals(Color.Green))
  42. {
  43. MessageBox.Show("Проверьте правильность настроек", "Неправильный формат данных",
  44. MessageBoxButtons.OK, MessageBoxIcon.Error); return;
  45. }
  46. SendBroadcast("{" + "\"serno\":" + '"' + SerialNo + '"' + "," + "\"dhcp\":" + '"' + dhcp + '"' + "," + "\"ipaddress\":" + '"' + textBox1.Text + '"' + "," + "\"gateway\":" + '"' + textBox2.Text + '"' + ","
  47. + "\"mask\"" + ":" + '"' + textBox3.Text + '"' + "}");
  48. messages.Clear();
  49. isChanged = true;
  50. base.Close();
  51. }
  52. private void Button_Reset_Click(object sender, EventArgs e)
  53. {
  54. checkBox1.Checked = true;
  55. textBox1.Text = "192.168.1.2";
  56. textBox2.Text = "192.168.1.1";
  57. textBox3.Text = "255.255.255.0";
  58. dhcp = true;
  59. }
  60. protected void SendBroadcast(String message)
  61. {
  62. /*UdpClient client = new UdpClient();
  63. IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, UDP_TX_PORT);
  64. Byte[] bytes = Encoding.ASCII.GetBytes(message);
  65. try
  66. {
  67. client.Send(bytes, bytes.Length, ip);
  68. }
  69. catch (ThreadAbortException e)
  70. {
  71. MessageBox.Show("Ничего серьезного, попробуйте еще раз, но сли вы увидели данное сообщение то расскажите о нем разработчику", "Debug",
  72. MessageBoxButtons.OK, MessageBoxIcon.Error);
  73. }
  74. catch (Exception e)
  75. {
  76. //MessageBox.Show("Проблемы с отправкой на порт: " + UDP_TX_PORT, "Порт отправки занят",
  77. // MessageBoxButtons.OK, MessageBoxIcon.Error);
  78. MessageBox.Show("Порт занят, попробуйте еще раз", "Порт отправки занят",
  79. MessageBoxButtons.OK, MessageBoxIcon.Error);
  80. }
  81. finally
  82. {
  83. client.Close();
  84. }*/
  85. try
  86. {
  87. byte[] sendbuf = Encoding.ASCII.GetBytes(message);
  88. Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  89. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  90. IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, 49049);
  91. s.Connect(ep);
  92. s.SendTo(sendbuf, ep);
  93. s.Close();
  94. /* s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  95. s.EnableBroadcast = true;
  96. IPAddress broadcast = IPAddress.Broadcast;
  97. byte[] sendbuf = Encoding.ASCII.GetBytes(message);
  98. IPEndPoint ep = new IPEndPoint(broadcast, 49049);
  99. s.Bind(ep);
  100. s.Connect(ep);
  101. s.Send(sendbuf);*/
  102. }
  103. catch (Exception ex) { MessageBox.Show(ex.Message); }
  104. }
  105. private string GetBroadcastIP(string deviceIP)
  106. {
  107. string broad = String.Empty;
  108. string[] arr = deviceIP.Split('.');
  109. arr[0] = "255";
  110. arr[1] = "255";
  111. arr[2] = "255";
  112. arr[3] = "255";
  113. arr.ToList().ForEach(a => broad += a + '.');
  114. return broad.Remove(broad.Length - 1);
  115. }
  116. private void Sender()
  117. {
  118. try
  119. {
  120. while (true)
  121. {
  122. string str = "{" + "\"serno\":" + '"' + SerialNo + '"' + "," + "\"dhcp\":" + '"' /*+ dhcp*/ + '"' + "," + "\"ipaddress\":" + '"' + '"' + "," + "\"gateway\":" + '"' + '"' + "," + "\"mask\"" + ":" + '"' + '"' + "}";
  123. SendBroadcast(str);
  124. Thread.Sleep(delayTime);
  125. }
  126. }
  127. catch (ThreadAbortException e)
  128. {
  129. Thread.ResetAbort();
  130. return;
  131. }
  132. }
  133. public static bool CheckPortFree(int nPortNum)
  134. {
  135. bool bCheckResult = true;
  136. Socket s = null;
  137. try
  138. {
  139. s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  140. s.Bind(new IPEndPoint(IPAddress.Loopback, nPortNum));
  141. }
  142. catch (Exception e)
  143. {
  144. MessageBox.Show("Порт занят сторонним приложением", "Порт Занят",
  145. MessageBoxButtons.OK, MessageBoxIcon.Error);
  146. bCheckResult = false;
  147. }
  148. finally
  149. {
  150. s.Close();
  151. }
  152. return bCheckResult;
  153. }
  154. protected static List<IPAddress> GetMyIpList()
  155. {
  156. List<IPAddress> MyIpList = new List<IPAddress>();
  157. String strHostName = Dns.GetHostName();
  158. IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
  159. foreach (IPAddress ipaddress in iphostentry.AddressList)
  160. {
  161. MyIpList.Add(ipaddress);
  162. }
  163. return MyIpList;
  164. }
  165. private void StartListener()
  166. {
  167. Thread.Sleep(500);
  168. Thread sender = new Thread(this.Sender);
  169. sender.Start();
  170. try
  171. {
  172. if (CheckPortFree(UDP_RX_PORT))
  173. listener = new UdpClient(UDP_RX_PORT);
  174. else return;
  175. IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_RX_PORT);
  176. MyIpList = GetMyIpList();
  177. DateTime startTime = DateTime.Now;
  178. while (true)
  179. {
  180. if (listener.Available > 0)
  181. {
  182. byte[] bytes = listener.Receive(ref groupEP);
  183. if ((!MyIpList.Contains(groupEP.Address))
  184. && (Encoding.UTF8.GetString(bytes, 0, bytes.Length).StartsWith("{" + "\"serno\":" + '"' + SerialNo + '"')))
  185. {
  186. messages.Add(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
  187. Invoke((Action)(() => SetParams()));
  188. break;
  189. }
  190. }
  191. if (DateTime.Now.Subtract(startTime) >= new TimeSpan(0, 0, 0, 0, timeout))// функция выполняется в течении трех секунд
  192. {
  193. MessageBox.Show("Сетевые параметры этого устройства не были получены, попробуйте еще раз", "Настройки не получены",
  194. MessageBoxButtons.OK, MessageBoxIcon.Error);
  195. break;
  196. }
  197. }
  198. }
  199. catch (Exception e)
  200. {
  201. MessageBox.Show(e.Message + "\n In listener");
  202. }
  203. finally
  204. {
  205. sender.Abort();
  206. listener.Close();
  207. }
  208. }
  209. private void SetParams()
  210. {
  211. if (messages.Count > 0)
  212. {
  213. Dictionary<string, string> dict = new Dictionary<string, string>();
  214. try
  215. {
  216. dict = GetDictFromJson(messages[0]);
  217. checkBox1.Checked = dhcp = dict["dhcp"].ToLower().Equals("true") ? true : false;
  218. textBox1.Text = dict["ipaddress"];
  219. textBox2.Text = dict["gateway"];
  220. textBox3.Text = dict["mask"];
  221. }
  222. catch
  223. {
  224. MessageBox.Show("Ошибка при парсинге JSON");
  225. return;
  226. }
  227. //string recievedMessage = String.Empty;
  228. //string str1 = //(string)recievedMessage["dhcp"];
  229. //if (String.Equals(str1, "True"))
  230. //{
  231. // dhcp = true;
  232. //}
  233. //else
  234. //{
  235. // dhcp = false;
  236. //}
  237. //checkBox1.Checked = dhcp;
  238. //textBox1.Text = (string)recievedMessage["ipaddress"];
  239. //textBox2.Text = (string)recievedMessage["gateway"];
  240. //textBox3.Text = (string)recievedMessage["mask"];
  241. }
  242. }
  243. private Dictionary<string, string> GetDictFromJson(string jsonText)
  244. {
  245. return jsonText
  246. .Replace('"', ' ')
  247. .Split(new char[] { ',', '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
  248. .ToDictionary(
  249. s => s.Split(':')[0].Trim().ToLower(),
  250. s => s.Split(':')[1].Trim().ToLower());
  251. }
  252. private void checkBox1_CheckedChanged(object sender, EventArgs e)
  253. {
  254. if (checkBox1.Checked)
  255. {
  256. textBox1.ReadOnly = true;
  257. textBox2.ReadOnly = true;
  258. textBox3.ReadOnly = true;
  259. dhcp = true;
  260. }
  261. else
  262. {
  263. textBox1.ReadOnly = false;
  264. textBox2.ReadOnly = false;
  265. textBox3.ReadOnly = false;
  266. dhcp = false;
  267. }
  268. }
  269. void textBox_TextChanged_Verify(object sender, EventArgs e)
  270. {
  271. TextBox textBox = sender as TextBox;
  272. textBox.ForeColor = IsIpAddress(textBox.Text) ? Color.Green : Color.Red;
  273. }
  274. static bool IsIpAddress(string Address)
  275. {
  276. System.Text.RegularExpressions.Regex IpMatch =
  277. new System.Text.RegularExpressions.Regex(@"^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}$");
  278. return IpMatch.IsMatch(Address);
  279. }
  280. }
  281. }