C# 将字符串转换为ip, 判断字符串是否为ip, 有效的ip格式
using System;
using System.Net;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
string str = "127.0.0.1";
string ip = ConvertIPAddress(str);
if (!string.IsNullOrEmpty(ConvertIPAddress(ip)))
{
Console.WriteLine("有效ip: {0}", ip);
}
else
{
Console.WriteLine("无效ip");
}
Console.Read();
}
/// <summary>
/// 将字符串转换为IP
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string ConvertIPAddress(string str)
{
IPAddress tmpIp;
if (IPAddress.TryParse(str, out tmpIp))
{
return IPAddress.Parse(str).ToString();
}
else
{
return "";
}
}
}
}