/// <summary>
/// 添加靜態路由
/// </summary>
/// <returns></returns>
private int AddIpRouteEntries(){
HttpClient wc = new HttpClient();
int res=AddIpRouteEntriesFromFile("http://61.155.18.16:81/cernet.txt");
if(res!=0){
MessageBox.Show("不能下载路由列表,即将把常熟理工学院内部地址添加到系统路由表并通过VPN访问,其他地址继续通过原网络访问!");
return res;
}
res = AddIpRouteEntriesFromFile("http://61.155.18.16:81/userdefine.txt");
if (res != 0)
{
MessageBox.Show("不能下载路由列表,即将把常熟理工学院内部地址添加到系统路由表并通过VPN访问,其他地址继续通过原网络访问!");
return res;
}
res=AddIpRouteEntry("10.0.0.0","255.0.0.0");
return res;
}
private int AddIpRouteEntriesFromFile(string url){
int res = 0;
HttpClient wc = new HttpClient();
try
{
byte[] str = wc.DownloadData(url);
String restext = Encoding.Default.GetString(str);
String[] ads = restext.Split(new char[] { '\n' });
for (int i = 0; i < ads.Length; i++)
{
string ent = ads[i].Trim();
if (ent.Length != 0)
{
string[] xx = ent.Split(new char[] { ',' });
res = AddIpRouteEntry(xx[0], xx[1]);
if (res != 0)
return res;
}
}
}
catch (Exception exp)
{
return 1976;
}
return res;
}
/// <summary>
/// 添加靜態路由
/// </summary>
/// <param name="network"></param>
/// <param name="netmask"></param>
/// <returns></returns>
private int AddIpRouteEntry(string network,string netmask){
UInt32 dest = BitConverter.ToUInt32(IPAddress.Parse(network).GetAddressBytes(), 0);
UInt32 mask = BitConverter.ToUInt32(IPAddress.Parse(netmask).GetAddressBytes(), 0);
UInt32 nextHop = BitConverter.ToUInt32(IPAddress.Parse(this.ClientIp).GetAddressBytes(), 0);
return iphlpapi.createIpForwardEntry(dest, mask, nextHop, Convert.ToUInt32(this.interfaceIndex), metric);
}
/// <summary>
/// 獲取系統路由表中目標地址為0.0.0.0的路由項的metric
/// </summary>
private void GetMetric(){
IEnumerable<RouteEntry> ienum=iphlp.GetRoutesTable();
IEnumerator<RouteEntry> enums=ienum.GetEnumerator();
enums.MoveNext();
while(enums.Current!=null){
RouteEntry ent = enums.Current;
if (ent.Destination.Equals(IPAddress.Parse("0.0.0.0")))
{
metric=ent.Metric1;
return;
}
enums.MoveNext();
}
}
注意:如果不获取系统路由表中目标地址为0的项的metric而直接添加路由项(metric1=-1),则CreateIpForwardEntry()函数会返回87(Invalid parameter)
没有评论:
发表评论