• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IPEndPoint类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Net.IPEndPoint的典型用法代码示例。如果您正苦于以下问题:C# IPEndPoint类的具体用法?C# IPEndPoint怎么用?C# IPEndPoint使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IPEndPoint类属于System.Net命名空间,在下文中一共展示了IPEndPoint类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: getPage

// This example uses the IPEndPoint class and its members to display the home page 
// of the server selected by the user.

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace Mssc.Services.ConnectionManagement
{
  public class TestIPEndPoint
  {

    // The getPage method gets the server's home page content by 
    // recreating the server's endpoint from the original serialized endpoint.
    // Then it creates a new socket and connects it to the endpoint.
    private static string getPage(string server, SocketAddress socketAddress)
    {
      //Set up variables and string to write to the server.
      Encoding ASCII = Encoding.ASCII;
      string Get = "GET / HTTP/1.1\r\nHost: " + server + 
        "\r\nConnection: Close\r\n\r\n";
      Byte[] ByteGet = ASCII.GetBytes(Get);
      Byte[] RecvBytes = new Byte[256];
      String strRetPage = null;

      Socket socket = null;

      // Recreate the connection endpoint from the serialized information.
      IPEndPoint endpoint = new IPEndPoint(0,0);
      IPEndPoint clonedIPEndPoint = (IPEndPoint) endpoint.Create(socketAddress);
      Console.WriteLine("clonedIPEndPoint: " + clonedIPEndPoint.ToString());

      Console.WriteLine("Press any key to continue.");
      Console.ReadLine();

      try
      {
        // Create a socket object to establish a connection with the server.
        socket = 
          new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        // Connect to the cloned end point.
        socket.Connect(clonedIPEndPoint);
      }
      catch(SocketException e) 
      {
        Console.WriteLine("Source : " + e.Source);
        Console.WriteLine("Message : " + e.Message);
      }
      catch(Exception e)
      {
        Console.WriteLine("Source : " + e.Source);
        Console.WriteLine("Message : " + e.Message);
      }

      if (socket == null)
        return ("Connection to cloned endpoint failed");
      
      // Send request to the server.
      socket.Send(ByteGet, ByteGet.Length, 0);  
        
      // Receive the server  home page content.
      Int32 bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0);
   
      // Read the first 256 bytes.
      strRetPage = "Default HTML page on " + server + ":\r\n";
      strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

      while (bytes > 0)
      {
        bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0);
        strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
      }
      
      socket.Close();

      return strRetPage;
    }

    // The serializeEndpoint method serializes the endpoint and returns the 
    // SocketAddress containing the serialized endpoint data.
    private static SocketAddress serializeEndpoint(IPEndPoint endpoint)
    {
 
      // Serialize IPEndPoint details to a SocketAddress instance.
      SocketAddress socketAddress = endpoint.Serialize();
  
      // Display the serialized endpoint information.
      Console.WriteLine("Endpoint.Serialize() : " + socketAddress.ToString());
 
      Console.WriteLine("Socket.Family : " + socketAddress.Family);
      Console.WriteLine("Socket.Size : " + socketAddress.Size);

      Console.WriteLine("Press any key to continue.");
      Console.ReadLine();

      return socketAddress;
    }

    private static void displayEndpointInfo(IPEndPoint endpoint)
    {
      Console.WriteLine("Endpoint.Address : " + endpoint.Address);
      Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
      Console.WriteLine("Endpoint.Port : " + endpoint.Port);
      Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());

      Console.WriteLine("Press any key to continue.");
      Console.ReadLine();
    }

    // The serializeEndpoint method determines the server endpoint and then 
    // serializes it to obtain the related SocketAddress object.
    // Note that in the for loop a temporary socket is created to ensure that 
    // the current IP address format matches the AddressFamily type.
    // In fact, in the case of servers supporting both IPv4 and IPv6, an exception 
    // may arise if an IP address format does not match the address family type.
    private static SocketAddress getSocketAddress(string server, int port)
    {
      Socket tempSocket = null;
      IPHostEntry host = null;
      SocketAddress serializedSocketAddress = null;
    
      try
      {
        // Get the object containing Internet host information.
        host = Dns.Resolve(server);

        // Obtain the IP address from the list of IP addresses associated with the server.
        foreach(IPAddress address in host.AddressList)
        {
          IPEndPoint endpoint = new IPEndPoint(address, port);

          tempSocket = 
            new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

          tempSocket.Connect(endpoint);

          if(tempSocket.Connected)
          {
            // Display the endpoint information.
            displayEndpointInfo(endpoint);
            // Serialize the endpoint to obtain a SocketAddress object.
            serializedSocketAddress = serializeEndpoint(endpoint);
            break;
          }
          else
                    {
                        continue;
                    }
                }

        // Close the temporary socket.
        tempSocket.Close();
      }
    
      catch(SocketException e) 
      {
        Console.WriteLine("Source : " + e.Source);
        Console.WriteLine("Message : " + e.Message);
      }
      catch(Exception e)
      {
        Console.WriteLine("Source : " + e.Source);
        Console.WriteLine("Message : " + e.Message);
      }
      return serializedSocketAddress;
    }

    // The requestServerHomePage method obtains the server's home page and returns
    // its content.
    private static string requestServerHomePage(string server, int port) 
    {
      String strRetPage = null;

      // Get a socket address using the specified server and port.
      SocketAddress socketAddress = getSocketAddress(server, port);

      if (socketAddress == null)
        strRetPage = "Connection failed";
      else 
        // Obtain the server's home page content.
        strRetPage = getPage(server, socketAddress);
     
      return strRetPage;
    }
    
    // Show to the user how to use this program when wrong input parameters are entered.
    private static void showUsage() 
    {
      Console.WriteLine("Enter the server name as follows:");
      Console.WriteLine("\tcs_ipendpoint servername");
    }

    // This is the program entry point. It allows the user to enter 
    // a server name that is used to locate its current homepage.
    public static void Main(string[] args) 
    {
      string host= null;
      int port = 80;

      // Define a regular expression to parse user's input.
      // This is a security check. It allows only
      // alphanumeric input string between 2 to 40 character long.
      Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$");

      if (args.Length < 1)
            {
                showUsage();
            }
            else
      {
        string message = args[0];
        if ((rex.Match(message)).Success)
        {
          host = args[0];
          // Get the specified server home_page and display its content.
          string result = requestServerHomePage(host, port); 
          Console.WriteLine(result);
        }
        else
                {
                    Console.WriteLine("Input string format not allowed.");
                }
            }
    }
  }
}
开发者ID:.NET开发者,项目名称:System.Net,代码行数:230,代码来源:IPEndPoint


示例2: new IPEndPoint(IPAddress, int port)

//引入命名空间
using System;
using System.Net;


class MainClass
{
    public static void Main()
    {
        IPAddress test1 = IPAddress.Parse("192.168.1.1");
      IPEndPoint ie = new IPEndPoint(test1, 8000);
    
      Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());
      Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);
      Console.WriteLine("The address is: {0}, and the port is: {1}", ie.Address, ie.Port);
    
    }
}
开发者ID:C#程序员,项目名称:System.Net,代码行数:18,代码来源:IPEndPoint



注:本文中的System.Net.IPEndPoint类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Attachment类代码示例发布时间:2022-05-24
下一篇:
C# IPAddress类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap