Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Uri.CheckHostName ใน C# พร้อมตัวอย่าง


บทนำ

เมธอด Uri.CheckHostName() ใน C# ใช้กำหนดประเภทของชื่อโฮสต์ (hostname) ว่าเป็น DNS name, IPv4 address, IPv6 address หรือไม่รู้จัก (Unknown) คืนค่าเป็น enumeration UriHostNameType

ไวยากรณ์ (Syntax)

public static UriHostNameType CheckHostName (string host_name);

ตัวอย่างที่ 1: ตรวจสอบ localhost

using System;

public class Demo 
{
    public static void Main()
    {
        string strURI = "https://localhost";
        Console.WriteLine("URI = " + strURI);
        
        UriHostNameType res = Uri.CheckHostName(strURI);
        Console.WriteLine("Host type = " + res);
    }
}

ผลลัพธ์

URI = https://localhost
Host type = Unknown

ตัวอย่างที่ 2: ตรวจสอบชื่อโดเมนทั่วไป

using System;

public class Demo 
{
    public static void Main()
    {
        string strURI = "www.tutorialspoint.com";
        Console.WriteLine("URI = " + strURI);
        
        UriHostNameType res = Uri.CheckHostName(strURI);
        Console.WriteLine("Host type = " + res);
    }
}

ผลลัพธ์

URI = www.tutorialspoint.com
Host type = Dns

ค่าที่เป็นไปได้ของ UriHostNameType

  • Dns - ชื่อโดเมน DNS (เช่น www.example.com)
  • IPv4 - ที่อยู่ IPv4 (เช่น 192.168.1.1)
  • IPv6 - ที่อยู่ IPv6 (เช่น ::1 หรือ 2001:db8::1)
  • Unknown - ไม่สามารถระบุประเภทได้ (เช่น localhost, ชื่อ NetBIOS)
  • Basic - ชื่อโฮสต์พื้นฐาน (ไม่มีจุด)

สรุป

เมธอด Uri.CheckHostName() ช่วยให้สามารถตรวจสอบและจัดประเภทที่อยู่โฮสต์ได้อย่างรวดเร็ว ซึ่งมีประโยชน์ในการตรวจสอบข้อมูลนำเข้า (input validation) หรือการจัดการการเชื่อมต่อเครือข่าย