Check if IP is in LAN (behind firewalls and routers)

前端 未结 3 923
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 12:40

I\'ve been crawling in the web for about 5 hours now and couldn\'t find a solution for my problem:

My company is developing an educational game and I\'m writing an autou

3条回答
  •  萌比男神i
    2021-02-04 12:49

    You could take advantage of TTL. With a TTL of 1 the packet won't be able to make it to the internet:

    private static bool IsLanIP(IPAddress address)
    {
        var ping = new Ping();
        var rep = ping.Send(address, 100, new byte[] { 1 }, new PingOptions()
        {
            DontFragment = true,
            Ttl = 1
        });
        return rep.Status != IPStatus.TtlExpired && rep.Status != IPStatus.TimedOut && rep.Status != IPStatus.TimeExceeded;
    }
    

    However, remember that it is called an IPv4 mask for a reason - you can use it as one (so here is your algorithmic solution):

    private static bool IsLanIP(IPAddress address)
    {
        var interfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach (var iface in interfaces)
        {
            var properties = iface.GetIPProperties();
            foreach (var ifAddr in properties.UnicastAddresses)
            {
                if (ifAddr.IPv4Mask != null && 
                    ifAddr.Address.AddressFamily == AddressFamily.InterNetwork &&
                    CheckMask(ifAddr.Address, ifAddr.IPv4Mask, address))
                    return true;
            }
        }
        return false;
    }
    
    private static bool CheckMask(IPAddress address, IPAddress mask, IPAddress target)
    {
        if (mask == null)
            return false;
    
        var ba = address.GetAddressBytes();
        var bm = mask.GetAddressBytes();
        var bb = target.GetAddressBytes();
    
        if (ba.Length != bm.Length || bm.Length != bb.Length)
            return false;
    
        for (var i = 0; i < ba.Length; i++)
        {
            int m = bm[i];
    
            int a = ba[i] & m;
            int b = bb[i] & m;
    
            if (a != b)
                return false;
        }
    
        return true;
    }
    

提交回复
热议问题