標籤:
//方法一:
private void GetIP()
{
string hostName = Dns.GetHostName();//本機名
//System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//會警告GetHostByName()已到期,我運行時且只返回了一個IPv4的地址
System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//會返回所有地址,包括IPv4和IPv6
foreach (IPAddress ip in addressList)
{
listBox1.Items.Add(ip.ToString());
}
}
//方法二:使用IPHostEntry擷取本機區域網路地址
static string GetLocalIp()
{
string hostname = Dns.GetHostName();//得到本機名
//IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已到期,只得到IPv4的地址
<SPAN style="WHITE-SPACE: pre"> </SPAN> IPHostEntry localhost = Dns.GetHostEntry(hostname);
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}
//方法三:通過向網站向一些提供IP查詢的網站發送webrequest,然後分析返回的資料流
string strUrl = "提供IP查詢的網站的連結";
Uri uri = new Uri(strUrl);
WebRequest webreq = WebRequest.Create(uri);
Stream s = webreq .GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd();
int i = all.IndexOf("[") + 1;
//分析字串得到IP
return ip;
/*
我用的是http://www.ip.cn/getip.php?action=getip&ip_url=&from=web
(這種連結很容易找的,百度“IP”得到一些網站,分析一下網站的連結就能得到)
返回的資料是:
<div class="well"><p>當前 IP:<code>0.0.0.0</code> 來自:XX省XX市 電信</p><p>GeoIP: Beijing, China</p></div>
解析這段就行
*/
//方法四:通過擷取CMD裡ipconfig命令的結果來得到IP
private void GetIP6()
{
Process cmd = new Process();
cmd.StartInfo.FileName = "ipconfig.exe";//設定程式名
cmd.StartInfo.Arguments = "/all"; //參數
//重新導向標準輸出
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;//不顯示視窗(控制台程式是黑屏)
//cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暫時不明白什麼意思
/*
收集一下 有備無患
關於:ProcessWindowStyle.Hidden隱藏後如何再顯示?
hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName);
Win32Native.ShowWindow(hwndWin32Host, 1); //先FindWindow找到視窗後再ShowWindow
*/
cmd.Start();
string info = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
cmd.Close();
textBox1.AppendText(info);
}
C# 擷取本機IP