Index ¦ Archives ¦ Atom

Code to Get Machines IP Address on External Route

Here is some C# code to retrieve the IP address of a machine's external-facing internet address:

    static void Main(string[] args)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        s.Connect("google.com", 1);

        IPEndPoint ipAddr = s.LocalEndPoint as IPEndPoint;

        if (ipAddr != null)
        {
            Console.WriteLine(ipAddr.Address.ToString());
        }
    }

Coderrr wrote this up in ruby on his website and shows how to send an email when this IP changes.

© Steve Spigarelli. Built using Pelican. Theme by Giulio Fidente on github.