Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string to System.Net.IPAddress

how can i convert string to System.Net,IPAddress in C#/.net 3.5

i tried this but i got this error "Cannot convert type 'string' to 'System.Net.IPAddress'"

 public void Form1_Load(object sender, EventArgs e)
    {
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in File.ReadAllLines("proxy.txt"))
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
                textBox1.Text = ip.ToString();
            }
        }

   }
like image 658
user1608298 Avatar asked Aug 20 '12 12:08

user1608298


People also ask

How to convert string into IPAddress in c#?

ReadAllLines("proxy. txt"). Select(s => IPAddress. Parse(s))) { // ... }

What is System net IPAddress?

The IPAddress class contains the address of a computer on an IP network. Example. The following example creates an IPAddress instance and then uses that instance to perform a DNS query for host information: IPAddress myIP = IPAddress.

Is IP address a string?

An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four numbers — an example address might be 192.158. 1.38. Each number in the set can range from 0 to 255.


2 Answers

Use the static IPAddress.Parse method to parse a string into an IPAddress:

foreach (var ipLine in File.ReadAllLines("proxy.txt"))
{
    var ip = IPAddress.Parse(ipLine);
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
        textBox1.Text = ip.ToString();
    }
}

If the lines in the file are not always valid IP addresses, you may want to consider using TryParse to avoid any exceptions being thrown.

like image 74
Oded Avatar answered Nov 15 '22 14:11

Oded


The IPAddress.Parse method accepts a string.

foreach (string line in File.ReadAllLines("proxy.txt"))
{
    IPAddress ip = IPAddress.Parse(line);
    // ...
}
like image 21
Steven Doggart Avatar answered Nov 15 '22 14:11

Steven Doggart