黑马程序员技术交流社区
标题:
C# 获取局域网ip
[打印本页]
作者:
q55964133
时间:
2014-5-20 21:56
标题:
C# 获取局域网ip
public
static
string
GetIPAddress()
{
try
{
IPAddress[]
arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
foreach
(IPAddress ip in
arrIPAddresses)
{
if
(ip.AddressFamily.Equals(AddressFamily.InterNetwork))//IPv4
{
return
ip.ToString();
}
}
return
"unknow";
}
catch
{
return
"unknow";
}
finally
{
}
}
复制代码
作者:
方杰斌
时间:
2014-5-20 21:58
/// <summary>
/// 获取本机在局域网的IP地址
/// </summary>
/// <returns></returns>
private string GetLocalIPAddress()
{
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
string strNativeIP = "";
string strServerIP = "";
if (addressList.Length > 1)
{
strNativeIP = addressList[0].ToString();
strServerIP = addressList[1].ToString();
}
else if(addressList.Length==1)
{
strServerIP = addressList[0].ToString();
}
return strServerIP;
}
========================
/// <summary>
/// 获取本机的上网IP
/// </summary>
/// <returns></returns>
private string GetConnectNetAddress()
{
string strUrl = "http://www.ip138.com/ip2city.asp"; //获得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(); //读取网站返回的数据 格式:您的IP地址是:[x.x.x.x]
int i = all.IndexOf("[") + 1;
string tempip = all.Substring(i, 15);
string ip = tempip.Replace("]", "").Replace(" ", "").Replace("<", "");
return ip;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2