Eventos

[C#] ¿Cómo obtener la dirección IP?


Este tema lo abarcaremos desde 2 puntos de partida: Frontend y Backend.

Frontend

Simplemente quieres saber cual es tu IP Privada o Pública.
using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace GetIPAddress.Frontend
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //1.
            GetPrivateIP();

            //2.
            Console.WriteLine(GetPublicIP());

        }

        private static void GetPrivateIP()
        {
            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                foreach (var unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
                    if (unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine(networkInterface.Name);
                        Console.WriteLine(unicastAddress.Address.ToString());
                        Console.WriteLine();
                    }
        }

        private static string GetPublicIP()
        {
            string address;
            var webRequest = WebRequest.Create("http://checkip.dyndns.org/");
            using (var webResponse = webRequest.GetResponse())
            using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
                address = streamReader.ReadToEnd();

            int startIndex = address.IndexOf("Address: ") + 9;
            int lastIndex = address.LastIndexOf("</body>");
            address = address.Substring(startIndex, lastIndex - startIndex);

            return address;
        }
    }
}

Backend

Tienes una aplicación web y quieres saber la dirección IP de los usuarios que la usan. Para este ejemplo usare un proyecto ASP.NET MVC.
using System;
using System.Web.Mvc;

namespace GetIPAddress.Backend.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.ClientIPAddress = GetClientIPAddress();
            return View();
        }

        private string GetClientIPAddress()
        {
            string clientIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (String.IsNullOrEmpty(clientIPAddress))
                clientIPAddress = Request.ServerVariables["REMOTE_ADDR"];

            if (String.IsNullOrEmpty(clientIPAddress))
                clientIPAddress = Request.UserHostAddress;

            if (String.IsNullOrEmpty(clientIPAddress) || clientIPAddress.Trim() == "::1")
                clientIPAddress = "Unknown";

            try
            {
                clientIPAddress = clientIPAddress.Remove(clientIPAddress.IndexOf(':'));
            }
            catch { }

            return clientIPAddress;
        }
    }
}
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xaml Development | GetIPAddress</title>
</head>
<body>
    <div>
        <ip>@ViewBag.ClientIPAddress</ip>
        <hr />
        <footer>
            <p><a href="http://xamldevelopment.blogspot.com/2015/01/c-como-obtener-la-direccion-ip.html" target="_blank">[C#] ¿Cómo obtener la dirección IP? - Xaml Development</a></p>
        </footer>
    </div>
</body>
</html>
Una vez publicada esta aplicación web, ya podríamos hacer lo siguiente en algún cliente:
using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace GetIPAddress.Frontend
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("http://getipaddress.azurewebsites.net/ : " + GetIPAddress());
            Console.WriteLine();
        }

        private static string GetIPAddress()
        {
            string address;
            var webRequest = WebRequest.Create("http://getipaddress.azurewebsites.net/");
            using (var webResponse = webRequest.GetResponse())
            using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
                address = streamReader.ReadToEnd();

            int startIndex = address.IndexOf("<ip>") + 4;
            int lastIndex = address.LastIndexOf("</ip>");
            address = address.Substring(startIndex, lastIndex - startIndex);

            return address;
        }
    }
}

CodePlex

Código fuente disponible en: CSharp -> GetIPAddress

No hay comentarios.:

Publicar un comentario

Epicalsoft — Superheroic Software Development Blog Designed by Templateism.com Copyright © 2014

Con tecnología de Blogger.