.NET 3.x Уведомление клиента о смене IP адреса сервера - C#

Узнай цену своей работы

Формулировка задачи:

IP Динамический передача клиенту от сервера суть такая Server IP: 192.168.1.25 (локальный) Port: 7890 Client IP: 179.189.14.25 (внешний динамический) Port: 7890 тут будет связь клиента с сервером через интернет пока адресс внешний будет не меняться как только IP(Внешний) измениться то клиент уже не сможет сойдениться с сервером Я так понял клиент шлет серверу сообщение - а сервер отвечает на него это как удочку закинуть , и на удочку чепляеться рыбка если не закинуть то и рыбки не будет, в конкретном адресе пруда)) но если клиент слал первое сообщение , то сервер должен знать адресс клиента и может отреагировав на изменения своего IP отослать клиенту клиент приймет , и будет ловить рыбу уже у другом пруду )) Вот и спрашиваю можно ли так сделать )) вот мой Сервер
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. //using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using System.Windows.Forms;
  9. using WindowsFormsApplication_ip;
  10. using download_link;
  11. namespace Server
  12. {
  13. class Program
  14. {
  15. static Read_file readFile=new Read_file();
  16. static GetAddressIP getAddressIp=new GetAddressIP();
  17. static string[] read_file_ip_port()
  18. {
  19. string ip = String.Empty;
  20. int port = 0, ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0;
  21. string[] array=new string[2];
  22. string[] lines = readFile.Get_file_line("ip_address.txt", Encoding.GetEncoding(1251));
  23. try
  24. {
  25. lines = readFile.not_empty_array(lines);
  26. string[] ipstr = lines[0].Split('.');
  27. ip1 = Convert.ToInt32(ipstr[0]);
  28. ip2 = Convert.ToInt32(ipstr[1]);
  29. ip3 = Convert.ToInt32(ipstr[2]);
  30. ip4 = Convert.ToInt32(ipstr[3]);
  31. ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
  32. port = Convert.ToInt32(lines[1]);
  33. array[0] = ip;
  34. array[1] = port.ToString();
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.WriteLine("Ошибка: " + ex.Message);
  39. Console.ReadKey(true);
  40. Environment.Exit(0);
  41. }
  42. return array;
  43. }
  44. static void Main(string[] args)
  45. {
  46. form_consol("Сервер v 1.3");
  47. string ip = String.Empty;
  48. int port = 0,num=0;
  49. Console.Write("Номер IP Сетевой Адаптера: ");
  50. try
  51. {
  52. num = Convert.ToInt32(Console.ReadLine());
  53. num = num - 1;
  54. if (num<0)
  55. {
  56. Console.WriteLine("Ошибка номер IP не должен быть равен 0, или ниже нуля!");
  57. num = 0;
  58. }
  59. }
  60. catch (Exception ex)
  61. {
  62. Console.WriteLine("Введены символы, заместь номера IP :"+ex.Message);
  63. }
  64.  
  65. ip = getAddressIp.Get_Local_IP(num);
  66. port = Convert.ToInt32(read_file_ip_port()[1]);
  67. if (ip!=String.Empty && port!=0)
  68. {
  69. Console.WriteLine("Локальный IP: "+ip+" | Порт: "+port+"\n");
  70. //Сервер подключаеться к локальному своему IP ПК и порту 12000 что открыт через модем в инете
  71. TcpListener listner = new TcpListener(new IPEndPoint(IPAddress.Parse(ip), port));
  72. listner.Start();
  73. try
  74. {
  75.  
  76. while (true)
  77. {
  78. string messag = String.Empty;
  79. TcpClient client = listner.AcceptTcpClient();
  80. StreamReader sr = new StreamReader(client.GetStream());
  81. Console.WriteLine("Клиент : " + sr.ReadLine());
  82. StreamWriter sw = new StreamWriter(client.GetStream());
  83. sw.AutoFlush = true;
  84. Console.Write("Server : ");
  85. messag = Console.ReadLine();
  86. sw.WriteLine(messag);
  87. while (true)
  88. {
  89. Console.WriteLine("Клиент : " + sr.ReadLine());
  90. Console.Write("Server : ");
  91. messag = Console.ReadLine();
  92. sw.WriteLine(messag);
  93. }
  94. //sw.WriteLine("Пока");
  95. //client.Close();
  96. }
  97. }
  98. catch
  99. (Exception ex)
  100. {
  101. Console.WriteLine("Ошибка: " + ex.Message);
  102. Console.ReadKey(true);
  103. Environment.Exit(0);
  104. }
  105. }
  106. }
  107. static void form_consol(string title)
  108. {
  109. Console.BackgroundColor = ConsoleColor.DarkCyan;
  110. Console.Clear();
  111. Console.ForegroundColor = ConsoleColor.White;
  112. Console.Title = title;
  113. }
  114. }
  115. }
Клиент
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. //using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7. using System.IO;
  8. using System.Reflection;
  9. using System.Windows.Forms;
  10. using download_link;
  11. namespace Client
  12. {
  13. class Program
  14. {
  15. static Read_file readFile = new Read_file();
  16. static string[] read_file_ip_port(string fileread)
  17. {
  18. string ip = String.Empty;
  19. int port = 0, ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0;
  20. string[] array = new string[2];
  21. string[] lines = readFile.Get_file_line(fileread, Encoding.GetEncoding(1251));
  22. try
  23. {
  24. lines = readFile.not_empty_array(lines);
  25. string[] ipstr = lines[0].Split('.');
  26. ip1 = Convert.ToInt32(ipstr[0]);
  27. ip2 = Convert.ToInt32(ipstr[1]);
  28. ip3 = Convert.ToInt32(ipstr[2]);
  29. ip4 = Convert.ToInt32(ipstr[3]);
  30. ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
  31. port = Convert.ToInt32(lines[1]);
  32. array[0] = ip;
  33. array[1] = port.ToString();
  34. }
  35. catch (Exception ex)
  36. {
  37. Console.WriteLine("Ошибка: " + ex.Message);
  38. Console.ReadKey(true);
  39. Environment.Exit(0);
  40. }
  41. return array;
  42. }
  43. static void Main(string[] args)
  44. {
  45. form_consol("Клиент v 1.3");
  46. string fileaddress = "address.pr";
  47. try
  48. {
  49. string ip=String.Empty;
  50. int port = 0,ip1=0,ip2=0,ip3=0,ip4=0;
  51. ip = read_file_ip_port(fileaddress)[0];
  52. port = Convert.ToInt32(read_file_ip_port(fileaddress)[1]);
  53. if (File.Exists(fileaddress) ==false)
  54. {
  55. Console.Write("Введите IP: ");
  56. ip1 = Convert.ToInt32(Console.ReadLine());
  57. Console.Clear();
  58. Console.Write("Введите IP: " + ip1+".");
  59. ip2 = Convert.ToInt32(Console.ReadLine());
  60. Console.Clear();
  61. Console.Write("Введите IP: " + ip1 + "."+ip2+".");
  62. ip3 = Convert.ToInt32(Console.ReadLine());
  63. Console.Clear();
  64. Console.Write("Введите IP: " + ip1 + "."+ip2+"."+ip3+".");
  65. ip4 = Convert.ToInt32(Console.ReadLine());
  66. Console.Clear();
  67. Console.Write("Введите IP: " + ip1 + "."+ip2+"."+ip3+"."+ip4+"\n");
  68. ip = ip1 + "."+ip2+"."+ip3+"."+ip4;
  69. Console.WriteLine("\n\nСойдинение по IP: "+ip);
  70. Console.Write("\n\nВведите Порт: ");
  71. port = Convert.ToInt32(Console.ReadLine());
  72. }
  73. if (ip!=String.Empty && port!=0)
  74. {
  75. Console.Clear();
  76. TcpClient client = new TcpClient();
  77. Console.WriteLine("Подождите идет сойдинение....");
  78. //Клиент подключаеться к внешнему IP и открытому порту 12000 в инете
  79. //Console.WriteLine(ip);
  80. client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
  81. Console.Clear();
  82. while (true)
  83. {
  84. string mssage = String.Empty;
  85. StreamWriter sw = new StreamWriter(client.GetStream());
  86. sw.AutoFlush = true;
  87. Console.Write("Клиент : ");
  88. //sw.WriteLine("Привет");
  89. mssage = Console.ReadLine();
  90. sw.WriteLine(mssage);
  91. StreamReader sr = new StreamReader(client.GetStream());
  92. Console.WriteLine("Server : " + sr.ReadLine());
  93. while (true)
  94. {
  95. Console.Write("Клиент : ");
  96. mssage = Console.ReadLine();
  97. sw.WriteLine(mssage);
  98. //sw.WriteLine("Пока");
  99. Console.WriteLine("Server : " + sr.ReadLine());
  100. }
  101. //client.Close();
  102. //Console.ReadKey();
  103. }
  104. }
  105. else
  106. {
  107. Console.Clear();
  108. Console.WriteLine("Данные IP и Port , не могут быть пусты!");
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. Console.Clear();
  114. Console.WriteLine("Ошибка: "+ex.Message);
  115. Console.ReadKey(true);
  116. Environment.Exit(0);
  117. }
  118. }
  119. static void form_consol(string title)
  120. {
  121. Console.BackgroundColor=ConsoleColor.DarkCyan;
  122. Console.Clear();
  123. Console.ForegroundColor=ConsoleColor.White;
  124. Console.Title = title;
  125. }
  126. }
  127. }
подкинте пример на C# как это можно , или нельзя осушетвить

Решение задачи: «.NET 3.x Уведомление клиента о смене IP адреса сервера»

textual
Листинг программы
  1. IPHostEntry ipHost = Dns.GetHostEntry(rsa.decode("chat.example.com");
  2. IPAddress ip = ipHost.AddressList[0];
  3.  
  4. //плевать как будет меняться внешний ip, его можно всегда получить хостом
  5. //ip вяжем к клиенту и так далее..

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 4.375 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы