【问题标题】:Convert IP Address into int, (ie inet aton in c#) [duplicate]将IP地址转换为int,(即c#中的inet aton)[重复]
【发布时间】:2011-06-05 21:20:44
【问题描述】:

可能的重复:
.NET Equivalant for INET_NTOA and INET_ATON
How to convert an IPv4 address into a integer in C#?

如何在 c# 中执行相同的 unix 函数 inet_aton?

【问题讨论】:

  • 我猜001自己什么都做不了。

标签: c# string int ip


【解决方案1】:

Try this 我认为是同一个问题,它有一个答案(享受)

【讨论】:

  • 这应该是投票结束。
【解决方案2】:

查看 IPAddress 类的 IPAddress.Parse(或 TryParse)方法。

一个例子是:

static int IPStringToInt(string ipAddress)
{
    IPAddress address = IPAddress.Parse(ipAddress);
    byte[] asBytes = address.GetAddressBytes();

    if(asBytes.Length != 4)
    {
        throw new ArgumentException("IP Address must be an IPv4 address");
    }

    return BitConverter.ToInt32(asBytes, 0);
}

您需要考虑字节的主机和网络顺序,但 IPAddress 类中有几个静态方法可以处理这些问题。

【讨论】:

    【解决方案3】:
    public int ToInteger(int A, int B, int C, int D)
    {
        return Convert.ToInt32((A* Math.Pow(256, 3)) + (B* Math.Pow(256, 2)) + (C* 256) + D);
    }
    

    http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx

    您可以像我一样扩展自己的 IP 类。

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2015-01-11
      • 2019-05-13
      • 2012-11-27
      • 2014-12-18
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多