/samples/snippets/csharp/VS_Snippets_Remoting/System.Net.IPEndPoint/CS/ipendpoint.cs

https://github.com/dotnet/dotnet-api-docs · C# · 254 lines · 153 code · 42 blank · 59 comment · 8 complexity · 526fab07e8f386fcd624ce4def31c9d3 MD5 · raw file

  1. // File name:ipendpoint.cs.
  2. // <Internal>
  3. // This program contains snippets applicable to the following:
  4. // System.Net.IPEndPoint (Snippet1);
  5. // System.Net.IPEndPoint.IPEndPoint(IPAddress, int) (Snippet2);
  6. // System.Net.IPEndPoint.Address (Snippet3);
  7. // System.Net.IPEndPoint.AddressFamily (Snippet3);
  8. // System.Net.IPEndPoint.Port (Snippet3);
  9. // System.Net.IPEndPoint.Serialize (Snippet4);
  10. // System.Net.IPEndPoint.Create (Snippet5);
  11. // </Internal>
  12. //<Snippet1>
  13. // This example uses the IPEndPoint class and its members to display the home page
  14. // of the server selected by the user.
  15. using System;
  16. using System.Text;
  17. using System.IO;
  18. using System.Net;
  19. using System.Net.Sockets;
  20. using System.Text.RegularExpressions;
  21. namespace Mssc.Services.ConnectionManagement
  22. {
  23. public class TestIPEndPoint
  24. {
  25. // The getPage method gets the server's home page content by
  26. // recreating the server's endpoint from the original serialized endpoint.
  27. // Then it creates a new socket and connects it to the endpoint.
  28. private static string getPage(string server, SocketAddress socketAddress)
  29. {
  30. //Set up variables and string to write to the server.
  31. Encoding ASCII = Encoding.ASCII;
  32. string Get = "GET / HTTP/1.1\r\nHost: " + server +
  33. "\r\nConnection: Close\r\n\r\n";
  34. Byte[] ByteGet = ASCII.GetBytes(Get);
  35. Byte[] RecvBytes = new Byte[256];
  36. String strRetPage = null;
  37. Socket socket = null;
  38. //<Snippet5>
  39. // Recreate the connection endpoint from the serialized information.
  40. IPEndPoint endpoint = new IPEndPoint(0,0);
  41. IPEndPoint clonedIPEndPoint = (IPEndPoint) endpoint.Create(socketAddress);
  42. Console.WriteLine("clonedIPEndPoint: " + clonedIPEndPoint.ToString());
  43. //</Snippet5>
  44. Console.WriteLine("Press any key to continue.");
  45. Console.ReadLine();
  46. try
  47. {
  48. // Create a socket object to establish a connection with the server.
  49. socket =
  50. new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  51. // Connect to the cloned end point.
  52. socket.Connect(clonedIPEndPoint);
  53. }
  54. catch(SocketException e)
  55. {
  56. Console.WriteLine("Source : " + e.Source);
  57. Console.WriteLine("Message : " + e.Message);
  58. }
  59. catch(Exception e)
  60. {
  61. Console.WriteLine("Source : " + e.Source);
  62. Console.WriteLine("Message : " + e.Message);
  63. }
  64. if (socket == null)
  65. return ("Connection to cloned endpoint failed");
  66. // Send request to the server.
  67. socket.Send(ByteGet, ByteGet.Length, 0);
  68. // Receive the server home page content.
  69. Int32 bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0);
  70. // Read the first 256 bytes.
  71. strRetPage = "Default HTML page on " + server + ":\r\n";
  72. strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
  73. while (bytes > 0)
  74. {
  75. bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0);
  76. strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
  77. }
  78. socket.Close();
  79. return strRetPage;
  80. }
  81. //<Snippet4>
  82. // The serializeEndpoint method serializes the endpoint and returns the
  83. // SocketAddress containing the serialized endpoint data.
  84. private static SocketAddress serializeEndpoint(IPEndPoint endpoint)
  85. {
  86. // Serialize IPEndPoint details to a SocketAddress instance.
  87. SocketAddress socketAddress = endpoint.Serialize();
  88. // Display the serialized endpoint information.
  89. Console.WriteLine("Endpoint.Serialize() : " + socketAddress.ToString());
  90. Console.WriteLine("Socket.Family : " + socketAddress.Family);
  91. Console.WriteLine("Socket.Size : " + socketAddress.Size);
  92. Console.WriteLine("Press any key to continue.");
  93. Console.ReadLine();
  94. return socketAddress;
  95. }
  96. //</Snippet4>
  97. //<Snippet3>
  98. private static void displayEndpointInfo(IPEndPoint endpoint)
  99. {
  100. Console.WriteLine("Endpoint.Address : " + endpoint.Address);
  101. Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
  102. Console.WriteLine("Endpoint.Port : " + endpoint.Port);
  103. Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());
  104. Console.WriteLine("Press any key to continue.");
  105. Console.ReadLine();
  106. }
  107. //</Snippet3>
  108. // The serializeEndpoint method determines the server endpoint and then
  109. // serializes it to obtain the related SocketAddress object.
  110. // Note that in the for loop a temporary socket is created to ensure that
  111. // the current IP address format matches the AddressFamily type.
  112. // In fact, in the case of servers supporting both IPv4 and IPv6, an exception
  113. // may arise if an IP address format does not match the address family type.
  114. private static SocketAddress getSocketAddress(string server, int port)
  115. {
  116. Socket tempSocket = null;
  117. IPHostEntry host = null;
  118. SocketAddress serializedSocketAddress = null;
  119. try
  120. {
  121. // Get the object containing Internet host information.
  122. host = Dns.Resolve(server);
  123. // <Snippet2>
  124. // Obtain the IP address from the list of IP addresses associated with the server.
  125. foreach(IPAddress address in host.AddressList)
  126. {
  127. IPEndPoint endpoint = new IPEndPoint(address, port);
  128. tempSocket =
  129. new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  130. tempSocket.Connect(endpoint);
  131. if(tempSocket.Connected)
  132. {
  133. // Display the endpoint information.
  134. displayEndpointInfo(endpoint);
  135. // Serialize the endpoint to obtain a SocketAddress object.
  136. serializedSocketAddress = serializeEndpoint(endpoint);
  137. break;
  138. }
  139. else
  140. {
  141. continue;
  142. }
  143. }
  144. // </Snippet2>
  145. // Close the temporary socket.
  146. tempSocket.Close();
  147. }
  148. catch(SocketException e)
  149. {
  150. Console.WriteLine("Source : " + e.Source);
  151. Console.WriteLine("Message : " + e.Message);
  152. }
  153. catch(Exception e)
  154. {
  155. Console.WriteLine("Source : " + e.Source);
  156. Console.WriteLine("Message : " + e.Message);
  157. }
  158. return serializedSocketAddress;
  159. }
  160. // The requestServerHomePage method obtains the server's home page and returns
  161. // its content.
  162. private static string requestServerHomePage(string server, int port)
  163. {
  164. String strRetPage = null;
  165. // Get a socket address using the specified server and port.
  166. SocketAddress socketAddress = getSocketAddress(server, port);
  167. if (socketAddress == null)
  168. strRetPage = "Connection failed";
  169. else
  170. // Obtain the server's home page content.
  171. strRetPage = getPage(server, socketAddress);
  172. return strRetPage;
  173. }
  174. // Show to the user how to use this program when wrong input parameters are entered.
  175. private static void showUsage()
  176. {
  177. Console.WriteLine("Enter the server name as follows:");
  178. Console.WriteLine("\tcs_ipendpoint servername");
  179. }
  180. // This is the program entry point. It allows the user to enter
  181. // a server name that is used to locate its current homepage.
  182. public static void Main(string[] args)
  183. {
  184. string host= null;
  185. int port = 80;
  186. // Define a regular expression to parse user's input.
  187. // This is a security check. It allows only
  188. // alphanumeric input string between 2 to 40 character long.
  189. Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$");
  190. if (args.Length < 1)
  191. {
  192. showUsage();
  193. }
  194. else
  195. {
  196. string message = args[0];
  197. if ((rex.Match(message)).Success)
  198. {
  199. host = args[0];
  200. // Get the specified server home_page and display its content.
  201. string result = requestServerHomePage(host, port);
  202. Console.WriteLine(result);
  203. }
  204. else
  205. {
  206. Console.WriteLine("Input string format not allowed.");
  207. }
  208. }
  209. }
  210. }
  211. }
  212. //</Snippet1>