Last active
August 29, 2015 14:10
-
-
Save DerKnerd/ff9c34087955efce0970 to your computer and use it in GitHub Desktop.
This Gist gets all local available IP addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Linq; | |
namespace tester { | |
public static class iptester { | |
public static IPAddress GetServerIP() { | |
var localIP = getMyAddress(); | |
var subnetmask = getSubnetMask(localIP); | |
for (byte p1 = 1; p1 < subnetmask[0]; p1++) { | |
for (byte p2 = 1; p2 < subnetmask[1]; p2++) { | |
for (byte p3 = 1; p3 < subnetmask[2]; p3++) { | |
for (byte p4 = 1; p4 < subnetmask[3]; p4++) { | |
var ip = new IPAdress(p1, p2, p3, p4); | |
if (trytoreach(ip)) { | |
return ip; | |
} | |
} | |
} | |
} | |
} | |
} | |
private static IPAddress getMyAddress() { | |
// http://stackoverflow.com/a/7661338 | |
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork); | |
} | |
private static IPAddress getSubnetMask(IPAddress address) { | |
// I have no idea how to get the subnet mask | |
return default(IPAddress); | |
} | |
private static bool trytoreach(IPAddress ip) { | |
var bytes = ip.GetAddressBytes(); | |
var req = (HttpWebRequest)WebRequest.CreateHttp(string.Format("http://{0}.{1}.{2}.{3}/iamhere", bytes[0], bytes[1], bytes[2], bytes[3])); | |
using (var resp = (HttpWebResponse)req.GetResponse()) { | |
if (resp.StatusCode == 200) { | |
return true; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment