2013年8月30日 星期五

【C#】 Get Computer IP Address 取得電腦UP位置

程式:自動找出本機端的所有IP位置

using System.Net;


private void Main(object sender, EventArgs e)
{    
    string server = null;
    server = Dns.GetHostName();
    IPAddresses(server);    
}

private static void IPAddresses(string server)
{
    try
    {    
        //取得本機名稱
        IPHostEntry heserver = Dns.GetHostEntry(server);

        //取得所有IP資訊
        foreach (IPAddress curAdd in heserver.AddressList)
        {
            //如果網際網路通訊協定是第6版(TCP/IPv6): InternNetworkV6.
            //如果網際網路通訊協定是第4版(TCP/IPv4): InternNetwork.
            Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());

            //如果網際網路通訊協定是第6版(TCP/IPv6),可取得IPv6 address scope identifier
            if (curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
                Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
            
            //顯示IP位置
            Console.WriteLine("Address: " + curAdd.ToString());

            //顯示二進制的IP位置
            Console.Write("AddressBytes: ");
            Byte[] bytes = curAdd.GetAddressBytes();
            for (int i = 0; i < bytes.Length; i++)
            {
                Console.Write(bytes[i]);
            }
            Console.WriteLine("\r\n");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("[DoResolve] Exception: " + e.ToString());
    }
}

0 意見:

張貼留言