Getting the IP address of server in ASP.NET?

前端 未结 6 1972
感情败类
感情败类 2020-11-30 03:53

How do I get the IP address of the server that calls my ASP.NET page? I have seen stuff about a Response object, but am very new at c#. Thanks a ton.

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 04:10

    The above is slow as it requires a DNS call (and will obviously not work if one is not available). You can use the code below to get a map of the current pc's local IPV4 addresses with their corresponding subnet mask:

    public static Dictionary GetAllNetworkInterfaceIpv4Addresses()
    {
        var map = new Dictionary();
    
        foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            foreach (var uipi in ni.GetIPProperties().UnicastAddresses)
            {
                if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;
    
                if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
                map[uipi.Address] = uipi.IPv4Mask;
            }
        }
        return map;
    }
    

    warning: this is not implemented in Mono yet

提交回复
热议问题