Asp.net: Get local IP address of system/machine

In this article I am going to explain how to get local IP address of system/machine using asp.net.
.

 Implementation:
Add webform to project.

HTML markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <fieldset style="width:450px">
        <legend>Local IP address</legend>
        <asp:Button ID="btnsubmit" runat="server" Text="Get IP address"/>
    &nbsp;<br />
        Local IP address is : <asp:Label ID="Label1" runat="server" BackColor="White" Font-Bold="True" ForeColor="Red"></asp:Label>
    </fieldset>
    </div>
    </form>
</body>
</html>

Add namespace 
C#
using System.Net;
using System.Net.Sockets;

VB.net
Imports System.Net
Imports System.Net.Sockets

On button click write the below given code:
C#
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        string ipAddress= Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
        Label1.Text = ipAddress.ToString();
    }

VB.net
  Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
        Dim ipAddress As String = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(Function(ip) ip.AddressFamily = AddressFamily.InterNetwork).ToString()
        Label1.Text = ipAddress.ToString()
    End Sub

Asp.net Get local IP address of systemmachine


Post a Comment

0 Comments