1.如果你是通过路由上网的,可以通过访问ip138之类的地址来获取外网IP
2.如果是通过PPPOE拨号上网的,可以使用以下代码获取IP
//获取宽带连接(PPPOE拨号)的IP地址,timeout超时(秒),当宽带未连接或者连接中的时候获取不到IP
public static string GetIP_PPPOE(int timeout)
{
int i = timeout * 2;
while (i > 0)
{
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
bool havePPPOE = false;
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ppp)
{
havePPPOE = true;
IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息
if (ip.UnicastAddresses.Count > 0)
{
return ip.UnicastAddresses[0].Address.ToString();
}
}
}
//当没有宽带连接的时候直接返回空
if (!havePPPOE) return "";
}
catch (Exception ex)
{
Console.WriteLine("获取宽带拨号IP出错:" + ex.Message);
}
i--;
Thread.Sleep(500);
}
return "";
}