How to remove port number from an IP address string

Ben*_*ton 3 .net c# string listbox

i am trying to separate the IP from the port in a list box. but i am only leaving the port number and ":" how would i make it so the ":" is removed and only the IP is left.

ips look like this:

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;
        }
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以拆分字符串:

string ip = item.Split(":")[0]
Run Code Online (Sandbox Code Playgroud)

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

  • _点头_,但答案是针对未来看到这个问题的每个人的,而不仅仅是OP。我想人们可以编辑问题标题来指定 IPv4,以将那些答案超出范围的人排除在外。 (3认同)
  • 对于 IPv6 地址来说,这会表现得非常糟糕。 (2认同)

Mat*_*lko 5

You could parse it into a Uri and then inspect the Host value:

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
Run Code Online (Sandbox Code Playgroud)

这具有确保 URI 有效的额外好处,并且适用于不包含 a 的地址,:而 usingIndexOf(':')则不会,因此您必须进行额外检查以查看字符串.Contains是否首先