asp.net中c#擷取本機IP地址執行個體代碼

來源:互聯網
上載者:User

例1

 代碼如下 複製代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace CSharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(new Program().GetHostInfo());
            Console.ReadLine();
        }
        //擷取本地IPd等資訊
        protected string GetHostInfo()  
        {
            StringBuilder hostInfo = new StringBuilder("");
            IPAddress[] ipHost = Dns.GetHostAddresses(Dns.GetHostName());
            hostInfo.Append("本機名:");
            hostInfo.Append(Dns.GetHostName());
            hostInfo.Append("rn");
            hostInfo.Append("IP 位址:");
            hostInfo.Append("rn");

            foreach (IPAddress address in ipHost)
            {
                hostInfo.Append(address.ToString());
                hostInfo.Append("rn");
            }

            return hostInfo.ToString();
        }
    }
}


 

控制台輸出結果:

 本機名:meteor-PC
IP 位址:
fe80::a1a2:949c:1a51:5e6c%11
2002:b46f:20fa::b46f:20fa
169.254.94.108
180.111.32.250

例2

 代碼如下 複製代碼


public static IPAddress GetHostIP()
{
IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ip = ipe.AddressList[0];


return ip;
}
private String GetIPAddress()
{
String str;
String Result = "";
String hostName = Dns.GetHostName();
IPAddress[] myIP = Dns.GetHostAddresses(hostName);
foreach (IPAddress address in myIP)
{
str = address.ToString();
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= '0' && str[i] <= '9' || str[i] == '.') Result = str;
}
}
return Result;
}

例3

上面的方法滿足不了我的需求,然後我在Google搜了一些,並沒有個很好的辦法,於是自己摸索寫下了這個方法。如果覺得有些地方欠妥的

 代碼如下 複製代碼

/// <summary>
/// 得到本機IP
/// </summary>
private string GetLocalIP() 
{
    //本機IP地址
    string strLocalIP = "";
    //得到電腦名稱
    string strPcName = Dns.GetHostName();
    //得到本機IP地址數組
    IPHostEntry ipEntry = Dns.GetHostEntry(strPcName);
    //遍曆數組
    foreach(var IPadd in ipEntry.AddressList)
    {
        //判斷當前字串是否為正確IP地址
        if (IsRightIP(IPadd.ToString())) 
        {
            //得到本地IP地址
            strLocalIP = IPadd.ToString();
            //結束迴圈
            break;
        }
    }
 
    //返回本地IP地址
    return strLocalIP;
}
  

?//得到網關地址
private string GetGateway() 
{ 
    //網關地址
    string strGateway = "";
    //擷取所有網卡
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    //遍曆數組
    foreach (var netWork in nics)
    {
        //單個網卡的IP對象
        IPInterfaceProperties ip = netWork.GetIPProperties();
        //擷取該IP對象的網關
        GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
        foreach(var gateWay in gateways)
        {
            //如果能夠Ping通網關
            if(IsPingIP(gateWay.Address.ToString()))
            {
                //得到網關地址
                strGateway = gateWay.Address.ToString();
                //跳出迴圈
                break;
            }
        }
 
        //如果已經得到網關地址
        if (strGateway.Length > 0) 
        {
            //跳出迴圈
            break;
        }
    }
 
    //返回網關地址
    return strGateway;
}
  

?/// <summary>
/// 判斷是否為正確的IP地址
/// </summary>
/// <param name="strIPadd">需要判斷的字串</param>
/// <returns>true = 是 false = 否</returns>
public static bool IsRightIP(string strIPadd) 
{
    //利用Regex判斷字串是否符合IPv4格式
    if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"))
    {
        //根據小數點分拆字串
        string[] ips = strIPadd.Split('.');
        if (ips.Length == 4 || ips.Length == 6)
        {
            //如果符合IPv4規則
            if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                //正確
                return true;
            //如果不符合
            else
                //錯誤
                return false;
        }
        else
            //錯誤
            return false;
    }
    else
        //錯誤
        return false;
}
  

?/// <summary>
/// 嘗試Ping指定IP是否能夠Ping通
/// </summary>
/// <param name="strIP">指定IP</param>
/// <returns>true 是 false 否</returns>
public static bool IsPingIP(string strIP) 
{
    try
    {
        //建立Ping對象
        Ping ping = new Ping();
        //接受Ping傳回值
        PingReply reply = ping.Send(strIP, 1000);
        //Ping通
        return true;
    }
    catch
    {
        //Ping失敗
        return false;
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.