c# - How to convert a string to an IP address

Convert a String to an IP address
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can convert a String object to an IP address. The IPAddress class provides an Internet Protocol (IP) address.

IPAddress Parse(String) method overload converts an IP address String to an IPAddress instance. The IPAddress Parse(string ipString) has a required parameter named ‘ipString’. The ‘ipString’ is a String that contains an IP address in the dotted-quad notation for IPv4 and in the colon-hexadecimal notation for IPv6.

The IPAddress Parse() method returns an IPAddress instance. The IpAddress Parse(ipString string) method throws ArgumentNullException if the ‘ipString’ is null. It also throws FormatException if the ‘ipString’ is not a valid ID address.
string-to-ip-address.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //this line create a string variable.
        string stringOfIPAddress = "127.0.0.1";

        Label1.Text = "string of ip address............<br />";
        Label1.Text += stringOfIPAddress;

        //parse/convert string to ip address
        System.Net.IPAddress ip = System.Net.IPAddress.Parse(stringOfIPAddress);

        Label1.Text += "<br /><br />ip address............<br />";
        Label1.Text += ip;
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string to ip address</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - string to ip address
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="string to ip address"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples