最近自己用C#窗体做了个登录页面,需要连接数据库,在自己和别人的电脑上都能完美运行,但就是有一点,需要我自己去更换我的IP地址,非常的麻烦。
能不能用代码让程序自动获取我的IP地址
第一种 取本主机ip地址
public string GetLocalIp()
{undefined
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{undefined
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{undefined
AddressIP = _IPAddress.ToString();
}
}
return AddressIP;
}
```C#
第二种
/// <summary>
/// 取本机主机ip
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{undefined
try
{undefined
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; i < IpEntry.AddressList.Length; i++)
{undefined
//从IP地址列表中筛选出IPv4类型的IP地址
//AddressFamily.InterNetwork表示此IP为IPv4,
//AddressFamily.InterNetworkV6表示此地址为IPv6类型
if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{undefined
string ip = "";
ip = IpEntry.AddressList[i].ToString();
return IpEntry.AddressList[i].ToString();
}
}
return "";
}
catch (Exception ex)
{undefined
return ex.Message;
}
}
第三种 通过访问的网址来取IP
public static string GetIP()
{undefined
using (var webClient = new WebClient())
{undefined
try
{undefined
var temp = webClient.DownloadString("http://localhost:1234/WeatherWebForm.aspx");//一般指定网址
var ip = Regex.Match(temp, @"\[(?<ip>\d+\.\d+\.\d+\.\d+)]").Groups["ip"].Value;
return !string.IsNullOrEmpty(ip) ? ip : null;
}
catch (Exception ex)
{undefined
return ex.Message;
}
}
}
```C#