【问题标题】:Check my local ip with a path whether it is valid or not用路径检查我的本地 ip 是否有效
【发布时间】:2021-03-08 03:09:10
【问题描述】:

您好,我尝试检查我的 ip(在本地服务器上)是否有效并为其添加路径,但问题是当我测试“192.168.0.235/cmd”时它不被视为 ip 地址.html?c-31" 很好地显示在我的浏览器上。这是代码:

public static bool check_ip(string ip)
{
    //192.168.0.235/cmd.html?c=31
    string path_ip = ip + "/cmd.html?c=31"; // error not an ip
    Ping ping = new Ping();
    IPAddress address = IPAddress.Parse("path_ip");
    PingReply pong = ping.Send(address, 100);
    if (pong.Status == IPStatus.Success)
    {
        return true;
    }
    return false;
}

如何让我的函数检查带有路径的 ip(例如:“192.168.0.235/cmd.html?c-31”)?

【问题讨论】:

  • 您似乎对什么是 IP 感到困惑。您的 IP 是 192.168.0.235,没有附加字母。 ping 不会让您知道您的服务是否正在运行。正如@AthanasiosKataras 建议的那样,您最好使用 HttpClient。

标签: c# ip


【解决方案1】:

您应该只检查 ip 部分:

        public static bool check_ip(string ip)
        {
                //192.168.0.235/cmd.html?c=31
                string path_ip = ip + "/cmd.html?c=31"; // error not an ip
                Ping ping = new Ping();
                IPAddress address = IPAddress.Parse(ip);
                PingReply pong = ping.Send(address, 100);
                if (pong.Status == IPStatus.Success)
                {
                    return true;
                }
                return false;
        }

注意这样的行:

// "path_ip" is not the value of your variable, but a string value "path_ip"
IPAddress address = IPAddress.Parse("path_ip");

如果您想像浏览器一样检查 url:

using var client = new HttpClient();

var result = await client.GetAsync("http://192.168.0.235/cmd.html?c=31");
Console.WriteLine(result.StatusCode); // if the status code is in the 2XX range, you are ok.

【讨论】:

  • 不,我需要使用此路径“/cmd.html?c=31”检查 ip 以了解它是否是我的设备。
  • 该 ip 在您的网络中是唯一的。其余的只是一个网址。您正在有效地检查 url 是否在您的浏览器中响应,而不是 ip 本身。如果你想检查一个IP,那么这就是这样做的方法。如果您想查看 url 是否响应,请使用 HttpClient
猜你喜欢
  • 2011-09-06
  • 1970-01-01
  • 2013-04-06
  • 2014-05-05
  • 2011-05-05
  • 2016-05-14
  • 2022-12-15
  • 2011-09-06
  • 1970-01-01
相关资源
最近更新 更多