Project Description
"What is my IP?", is presumably the most fundamental question for every web surfer. Simple feature returning IP address could enhance the functionality of any ASP.NET web site, contributing to better user experience.

Simple feature could be added to any ASP.NET page returning the IP address.

Working DEMO is available at: http://www.webinfocentral.com (refer to the button “IP”)

Project contains following files:

1. GetMyIP.cs (class module written in C# to be placed in App_Code directory)
2. Default.aspx (sample web page contains a button control to pop-up JavaScript message, showing IP address)
3. WhatIsMyIP_screenshot.png (sample screenshot)

The code module (1) is rather straightforward: it's using HttpContext object to return IP address:

//******************************************************************************
// Module           :   GetMyIP.cs
// Author           :   Alexander Bell
// Copyright        :   2007-2009 Infosoft International Inc
// Description      :   Get my IP address

//******************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//******************************************************************************

using System;
using System.Web;

public static class MyIP {
    public static string Address {
        get {
            try {
                if (HttpContext.Current == null) return String.Empty;
                return HttpContext.Current.Request.UserHostAddress;
            }
            catch { return String.Empty; }
        }
    }
}


Sample Web Page contains single Button1 server control with "onclick" event added:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">

        <title>WHAT_IS_MY_IP | Infosoft International Inc</title>
        
        <script runat="server">
            protected void Page_Load(object sender, EventArgs e)
            {
                Button1.Attributes.Add("onclick", 
                "javascript:alert('Your IP address: " + MyIP.Address + "')"); 
            }
        </script>
        
    </head>

    <body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1"
                runat="server"
                Text="WHAT IS MY IP"
                UseSubmitBehavior="False" />
        </form>
    </body>
</html>


Sample screenshot showing IP address follows:
WhatIsMyIP_screenshot.png
Fig.1. Sample screenshot

 

Internet TCP/IP IP .NET ASP.NET JavaScript C# HTTP HttpContext UserHostAddress

Last edited Feb 18, 2015 at 3:15 AM by DrABELL, version 12