简体   繁体   English

如何使用C#asp.net获取系统IP(IPv4)地址并转换为字符串

[英]How to Get system IP (IPv4) address and convert to string using C# asp.net

On my web application I am using the following function to get System IP 在我的Web应用程序上,我正在使用以下功能来获取系统IP

Function 功能

public void SetHostid()
    {
        try
        {
            string ip = "";
            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();

            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

            IPAddress[] addr = ipEntry.AddressList;

            ip = addr[1].MapToIPv4().ToString();

            HostId = ip;
            HttpContext.Current.Session["Hostid"] = HostId;
        }
        catch (Exception ex)
        {
            Error_ManagerClass em = new Error_ManagerClass();
            em.WriteError(ex);
        }
    }

It works perfectly because the IP is on the 1 postion of the variable addr ( addr[ 1] ). 由于IP位于变量addr的addr[ 1]addr[ 1] )上,因此它可以完美地工作。 在此处输入图片说明

And the problem comes when I try to run the same solution from a different system. 当我尝试从不同的系统运行相同的解决方案时,问题就来了。 function throws an error while trynig to convert IP to string( ip = addr[1].MapToIPv4().ToString(); ) because IP is not in the position number 1. 尝试将IP转换为字符串时,函数将引发错误( ip = addr[1].MapToIPv4().ToString(); ),因为IP不在位置编号1中。
在此处输入图片说明

how can I change the function to work on every computer ?? 如何更改功能以在每台计算机上工作?

If you want to get IPv4 only use this code: 如果只想获取IPv4,请使用以下代码:

var addr = ipEntry.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork);

var firstInList = addr.First(); // get first

But you should consider which IP to chose when there are several IP addresses in system. 但是,当系统中有多个IP地址时,应考虑选择哪个IP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在asp.net中使用C#获取IP地址 - How to get the IP address using C# in asp.net 如何在不使用外部服务的情况下在ASP.NET中获取客户端的外部IPv4地址? - How to get client's external IPv4 address in ASP.NET without using external services? C#-WinRT-将IPv4地址从uint转换为字符串? - C# - WinRT - Convert IPv4 address from uint to string? 如何获取服务器 IP 地址(在 C#/asp.net 中)? - How to get the server IP Address (in C# / asp.net)? 如何在 C# 中将 IPv4 地址转换为整数? - How to convert an IPv4 address into a integer in C#? 如何使用登录用户的 ASP.NET C# 获取 Mac 和 IP 地址 - How to get Mac and IP address using ASP.NET C# of the login User 如何使用Asp.Net C#获取客户端IP地址-当我们的项目托管在IIS中时 - How to Get Client IP Address using Asp.Net C# - When our Project is Hosted in IIS 如何使用asp.net c#获取localhost的公共IP地址? - How to get the public IP address of localhost using asp.net c#? 如何获取客户端机器的 Mac 地址或 IPv4 地址以在 ASP.net core v3.1 中唯一标识机器 - How to get Mac Address OR IPv4 address of Client Machine to uniquely identify machine in ASP.net core v3.1 如何确定字符串是 C# 中的有效 IPv4 还是 IPv6 地址? - How to determine if a string is a valid IPv4 or IPv6 address in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM