考虑到电脑有多张网卡的情况,如果使用本机ip地址有可能就会出现获取网卡错误,所以自己写了一个从配置文件读取ip信息的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
namespace ipconfig{
public class IpConfig
{
string m_path, m_name;
public IpConfig(string path,string name)//路径名 + 文件名 c:\\config\\config.xml
{
m_path = path;
m_name ="/"+ name;
}
public string GetIp(int num)
{
int i;
string ip="";
try
{
if (!File.Exists(m_path + m_name))
{
DirectoryInfo d = Directory.CreateDirectory(m_path);
XmlDocument xmldoc = new XmlDocument();
//加入XML的声明段落
xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null));
//加入根元素
XmlElement xmlelem = xmldoc.CreateElement("", "AllIp", "");
xmldoc.AppendChild(xmlelem);
//FileName
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
for (i = 1; i <= ipHost.AddressList.Length; i++)
{//写ip到config。xml文件
XmlElement xmlelemFileName = xmldoc.CreateElement("Ip-" + i.ToString());
XmlText xmltextFileName = xmldoc.CreateTextNode(GetIPList(i));
xmlelemFileName.AppendChild(xmltextFileName);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelemFileName);
}
xmldoc.Save(m_path + m_name);
}
if (File.Exists(m_path + m_name))
ip = ReadIp(num);
else
ip = "can`t create ipconfig.xml";
}
catch (Exception ex)
{
ip = ex.Message;
}
return ip;
}
public string ReadIp(int IpNum)
{
string strIp="";
XmlElement xe;
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(m_path + m_name);
XmlNode xn = xmlDoc.SelectSingleNode("AllIp");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
xe = (XmlElement)xnf;
if("Ip-"+IpNum.ToString()==xnf.Name)
{
strIp = xe.InnerText;
break;
}
}
}
catch (Exception ex)
{
strIp= ex.Message;
}
return strIp;
}
private string GetIPList(int netcard) //获取iplist
{
try
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//考虑ipv6的情况 主要对应win7以上系统
int netCardCount = 0;
if (ipHost.AddressList.Length > 1)
{
string result = "255.255.255.255";
foreach (IPAddress ipaddr in ipHost.AddressList)
{
if (ipaddr.ToString().Length > result.Length)
{
netCardCount++;
}
}
}
IPAddress ipAddr = ipHost.AddressList[netcard + netCardCount - 1];
return ipAddr.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}