Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove port number from an IP address string

I am trying to separate the IP address from the port in a list box. But my code creates a string that contains both the port number and ":". How can ignore the ":" and keep only the IP?

IPs look like this:

192.168.0.12:80
192.168.0.2:123
192.168.0.3:1337

Here is my current code:

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;
}
like image 787
Ben Whittington Avatar asked Dec 08 '22 21:12

Ben Whittington


1 Answers

You could split the string:

string ip = item.Split(":")[0]

or you could create an Uri object and extract from it the Host value

like image 162
maxroma91 Avatar answered Dec 10 '22 11:12

maxroma91