Получение ip-адреса для сервера - C#

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

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

Здравствуйте. Пробую разобраться с сервером на c# сидя на mac с xamarin studio. При запуске проги идет попытка запустить сервер, но прога крашится из-за невозможности получения ip(не знаю почему). Хотя на винде все работает. Ругается на это
Листинг программы
  1. System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0];
Как исправить эту проблему? КЛАСС Program.cs
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace app
  6. {
  7. class Program
  8. {
  9. const int PORT = 90;
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine("Запустить сервер? Y | N");
  13. if (Console.ReadLine().Trim().ToUpper() == "Y")
  14. {
  15. //получение имени компъютера
  16. string host = System.Net.Dns.GetHostName();
  17. //получение ip
  18. System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0];
  19. Console.WriteLine("IP-адрес: " +ip.ToString());
  20. Server server = new Server(PORT, Console.Out);
  21. server.Work();
  22. }
  23. }
  24. }
  25. }
КЛАСС Server.cs
Листинг программы
  1. using System.Net;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. namespace app
  8. {
  9. class Server
  10. {
  11. public TcpListener Listener; // объект принимающий tcp-клиентов
  12. public List<ClientInfo> clients = new List<ClientInfo>();
  13. public List<ClientInfo> NewClients = new List<ClientInfo>();
  14. public static Server server;
  15. static System.IO.TextWriter Out;
  16. public Server(int Port, System.IO.TextWriter _Out)
  17. {
  18. Out = _Out;
  19. Server.server = this;
  20. //создаем слушателя для указанного порта
  21. Listener = new TcpListener(IPAddress.Any, Port);
  22. Listener.Start(); // запускаем его
  23. }
  24. public void Work()
  25. {
  26. Thread clientListener = new Thread(ListenerClients);
  27. clientListener.Start();
  28. while (true)
  29. {
  30. foreach (ClientInfo client in clients)
  31. {
  32. if (client.IsConnect)
  33. {
  34. NetworkStream stream = client.Client.GetStream();
  35. while (stream.DataAvailable)
  36. {
  37. int ReadByte = stream.ReadByte();
  38. if (ReadByte != -1)
  39. {
  40. client.buffer.Add((byte)ReadByte);
  41. }
  42. }
  43. if (client.buffer.Count > 0)
  44. {
  45. Out.WriteLine("Resend");
  46. foreach (ClientInfo otherClient in clients)
  47. {
  48. byte[] msg = client.buffer.ToArray();
  49. client.buffer.Clear();
  50. foreach (ClientInfo _otherClient in clients)
  51. {
  52. if (_otherClient != client)
  53. {
  54. try
  55. {
  56. _otherClient.Client.GetStream().Write(msg, 0, msg.Length);
  57. }
  58. catch
  59. {
  60. _otherClient.IsConnect = false;
  61. _otherClient.Client.Close();
  62. }
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }
  69. clients.RemoveAll(delegate (ClientInfo CI)
  70. {
  71. if (!CI.IsConnect)
  72. {
  73. Server.Out.WriteLine("Клиент отсоеденился");
  74. return true;
  75. }
  76. return false;
  77. });
  78. if (NewClients.Count > 0)
  79. {
  80. clients.AddRange(NewClients);
  81. NewClients.Clear();
  82. }
  83. }
  84. }
  85. //остановка сервера
  86. ~Server()
  87. {
  88. //если слушатель был создан
  89. if (Listener != null)
  90. {
  91. //остановим его
  92. Listener.Stop();
  93. }
  94. foreach (ClientInfo client in clients)
  95. {
  96. client.Client.Close();
  97. }
  98. }
  99. static void ListenerClients()
  100. {
  101. while (true)
  102. {
  103. server.NewClients.Add(new ClientInfo(server.Listener.AcceptTcpClient()));
  104. Out.WriteLine("Новый клиент");
  105. }
  106. }
  107. }
  108. class ClientInfo
  109. {
  110. public TcpClient Client;
  111. public List<byte> buffer = new List<byte>();
  112. public bool IsConnect;
  113. public ClientInfo(TcpClient Client)
  114. {
  115. this.Client = Client;
  116. IsConnect = true;
  117. }
  118. }
  119. }
P.S. Прога не моя, отсюда взял https://www.youtube.com/watch?v=-xtGcZkG1V4

Решение задачи: «Получение ip-адреса для сервера»

textual
Листинг программы
  1. using System.Net;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using System;
  8.  
  9. namespace Fchat
  10. {
  11.     class Server
  12.     {
  13.         public TcpListener Listener; //объект, принимающий TCP клиентов
  14.         public List<ClientInfo> clients = new List<ClientInfo>();
  15.         public List<ClientInfo> NewClients = new List<ClientInfo>();
  16.         public static Server server;
  17.         static System.IO.TextWriter Out;
  18.  
  19.         public Server(int Port, System.IO.TextWriter _Out)
  20.         {
  21.             Out = _Out;
  22.             Server.server = this;
  23.  
  24.             //создаем слушателя для указанного порта
  25.             Listener = new TcpListener(IPAddress.Any, Port);
  26.             Listener.Start(); //запускаем его
  27.         }
  28.  
  29.         public void Work()
  30.         {
  31.             Thread clientListener = new Thread(ListenerClients);
  32.             clientListener.Start();
  33.  
  34.             while (true)
  35.             {
  36.                 foreach (ClientInfo client in clients)
  37.                 {
  38.                     if (client.IsConnect)
  39.                     {
  40.                         NetworkStream stream = client.Client.GetStream();
  41.                         while (stream.DataAvailable)
  42.                         {
  43.                             int ReadByte = stream.ReadByte();
  44.                             if (ReadByte != -1)
  45.                             {
  46.                                 client.buffer.Add((byte)ReadByte);
  47.                             }
  48.                         }
  49.                         if (client.buffer.Count > 0)
  50.                         {
  51.                             Out.WriteLine("Resend");
  52.                             foreach (ClientInfo otherClient in clients)
  53.                             {
  54.                                 byte[] msg = client.buffer.ToArray();
  55.                                 client.buffer.Clear();
  56.                                 foreach (ClientInfo _otherClient in clients)
  57.                                 {
  58.                                     if (_otherClient != client)
  59.                                     {
  60.                                         try
  61.                                         {
  62.                                             _otherClient.Client.GetStream().Write(msg, 0, msg.Length);
  63.                                         }
  64.                                         catch
  65.                                         {
  66.                                             _otherClient.IsConnect = false;
  67.                                             _otherClient.Client.Close();
  68.                                         }
  69.                                     }
  70.                                 }
  71.                             }
  72.                         }
  73.                     }
  74.                 }
  75.                 clients.RemoveAll(delegate (ClientInfo CI)
  76.                    {
  77.                        if (!CI.IsConnect)
  78.                        {
  79.                            Server.Out.WriteLine("Клиент отсоеденился.");
  80.                            return true;
  81.                        }
  82.                        return false;
  83.                    });
  84.                 if (NewClients.Count > 0)
  85.                 {
  86.                     clients.AddRange(NewClients);
  87.                     NewClients.Clear();
  88.                 }
  89.             }
  90.         }
  91.         //остановка сервера
  92.         ~Server()
  93.         {
  94.             //если слушатель был создан
  95.             if (Listener != null)
  96.             {
  97.                 //остановим его
  98.                 Listener.Stop();
  99.             }
  100.             foreach (ClientInfo client in clients)
  101.             {
  102.                 client.Client.Close();
  103.             }
  104.  
  105.         }
  106.         static void ListenerClients()
  107.         {
  108.             while (true)
  109.             {
  110.                 server.NewClients.Add(new ClientInfo(server.Listener.AcceptTcpClient()));
  111.                 Out.WriteLine("Новый клиент.");
  112.             }
  113.         }
  114.     }
  115.  
  116.     class ClientInfo
  117.     {
  118.         public TcpClient Client;
  119.         public List<byte> buffer = new List<byte>();
  120.         public bool IsConnect;
  121.         public ClientInfo(TcpClient Client)
  122.         {
  123.             this.Client = Client;
  124.             IsConnect = true;
  125.         }
  126.     }
  127.  
  128.     class Program
  129.     {
  130.         const int PORT = 90;
  131.  
  132.         static void Main(string[] args)
  133.         {
  134.             Console.WriteLine("Запустить сервер? (Y / N)");
  135.             if (Console.ReadLine().Trim().ToUpper() == "Y")
  136.             {
  137.                 //получение имени компъютера
  138.                 IPHostEntry host = Dns.GetHostEntry("localhost");
  139.                 IPAddress ip = host.AddressList[0];
  140.                 IPEndPoint ipEndPoint = new IPEndPoint(ip, 11000);
  141.                 Socket sListener = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  142.                 Console.WriteLine("IP адрес " + ip.ToString());
  143.                 sListener.Bind(ipEndPoint);
  144.                 sListener.Listen(10);
  145.                 Server server = new Server(PORT, Console.Out);
  146.                 server.Work();
  147.             }
  148.         }
  149.     }
  150. }

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


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

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

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

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

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

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