如何从IP地址字符串中去除端口号

4

我试图从一个列表框中分离IP地址和端口。但是我的代码创建了一个同时包含端口号和":"的字符串。如何忽略":"并仅保留IP地址?

IPs看起来像这样:

192.168.0.12:80
192.168.0.2:123
192.168.0.3:1337

这是我的当前代码:

for (int i = 0; i < lb.Items.Count; i++)
{
    string item = lb.Items[i] as string;
    item = item.Substring(item.LastIndexOf(":"));
    lb.Items[i] = item;
}

9
item = item.Substring(0, item.LastIndexOf(':')); - itsme86
item = item.Split(':')[0]; - jallmen
5个回答

8
您可以将字符串拆分为以下部分:
string ip = item.Split(":")[0]

或者您可以创建一个 Uri 对象并从中提取 Host 值。

3
这在IPv6地址中会出现很严重的问题。 - Charles Duffy
@CharlesDuffy 没错,但是OP要求提供3个IPv4的例子。 - maxroma91
3
_nod_,但回答是给未来所有看到这个问题的人而不仅仅是提问者的。我认为可以编辑问题标题以指定IPv4,以排除那些超出范围的人。 - Charles Duffy

7
你可以将其解析为 Uri,然后检查 Host 值:
String ip = "192.168.0.3:1337";
Uri uri = new Uri("http://" + ip);
MessageBox.Show(uri.Port.ToString()); //shows 1337
MessageBox.Show(uri.Host.ToString()); //shows 192.168.0.3

这样做的另一个好处是确保URI有效,并且适用于不包含:的地址,而使用IndexOf(':')则不会,所以您需要进行额外的检查,以查看字符串是否.Contains它。

2

我知道这是一个非常老的问题。只是在这里发布一个解决方案,因为即使今天我也遇到了这个问题。

 private string GetIPAddress()
    {
      string ipaddress = string.Empty;
      if (HttpContext.Current != null)
      {
        ipaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipaddress))
          ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
      }

      if (!string.IsNullOrEmpty(ipaddress))
      {
        var splitList = ipaddress.Split(':');
        //For IPv6 - Format >> [1fff:0:a88:85a3::ac1f]:8001  - This will parse the value to get proper IP from IPv6 format.
        if (splitList.Length > 2)
        {
          ipaddress = IPAddress.Parse(ipaddress).ToString();
        }
        // For IPv4 - Format >> 192.168.0.3:1337  - This will only take value before : (colon)
        else if (splitList.Length == 2)
        {
          ipaddress = splitList[0];
        }

      }
      return ipaddress;
    }


希望这能帮助到某些人!

0

JavaScript方法

const uri = "192.168.0.3:1337";
  
const url = new URL(uri);
console.log(url.port); //shows 1337
console.log(url.hostname); //shows 192.168.0.3

这个答案有助于思考,链接如下:https://stackoverflow.com/posts/38617619/revisions


这是一个标记为C#的问题 - undefined

0
你可以使用正则表达式从IP地址中移除端口号,例如:
string input = "52.240.151.125:47042";
string pattern = ":\\d{1,5}";
string output = Regex.Replace(input, pattern, "");
Console.WriteLine(output);

你将获得以下输出

Regex output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接