c# - 如何在 C# 中从接收 CoAP 包中获取 IP 地址?

标签 c# coap

在 C# 中,我尝试获取 CoAP 客户端的 IP 地址。这可能吗?我尝试查看收到的交换对象,但似乎找不到 IP 地址。

客户端

    class Program
{
    private static string _port = "5683";

    static void Main(string[] args)
    {
        Request request = new Request(Method.GET);

        Uri uri = new Uri("coap://127.0.0.1:" + _port + "/" + "Test");
        request.URI = uri;
        byte[] payload = Encoding.ASCII.GetBytes("test");
        request.Payload = payload;
        request.Send();

        // wait for one response
        Response response = request.WaitForResponse();
        Debug.WriteLine(response);
    }
}

服务器

        public Task<string> OpenAsync(CancellationToken cancellationToken)
    {
        try
        {
            _server = new CoapServer(_port);
            _server.Add(new MessageResource(_path);
            _server.Start();

        } catch (Exception ex)
        {
            throw;
        }
    }

消息资源(用于服务器)

 public class MessageResource : CoAP.Server.Resources.Resource
{
    public MessageResource(string path) : base(path)
    {
    }
    protected async override void DoGet(CoapExchange exchange)
    {
        try
        {
            var payload = exchange.Request.Payload;
            if (payload != null)
            {
                exchange.Respond(payloadString);
            } else
            {
                throw new Exception("Payload is null. No actor has been made.");
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

如您所见,我想接收发送消息的客户端的 IP 地址。我已尝试检查交换对象的所有属性,但我似乎找不到可以使用的 IP 地址。

最佳答案

显然,IP 地址是在 Exchange.Request.Source.ToString() 下找到的。如果您从 localhost 而不是 127.0.0.1 发送包,它只会显示 localhost 并且更难找到。

"Uri uri = new Uri("coap://localhost:" + _port + "/" + "Test");"

编辑:另外,也许对于 future 需要这个的人来说:如果您只需要IP地址或端口,请不要拆分exchange.Request.Source。 Visual Studio 自动解析 Exchange.Request.Source 到 Endpoint。这应该是 IPEndpoint 而不是 Endpoint,因为如果它是 Endpoint,它会丢失“地址”和“端口”属性。您可以像这样修复它:

        if (exchange.Request.Source is IPEndPoint p)
        {
            //p.Address
            //p.Port
        }
        else
        {
            //Handle errors here
        }

关于c# - 如何在 C# 中从接收 CoAP 包中获取 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52698094/

相关文章:

c# - 我们如何在一行中调用多个可选函数?

security - DTLS 是否需要 session 超时?

java - CoAP 服务器无法启动

http - HTTP 和 COAP 之间的主要区别是什么?

javascript - Vue.js 可以使用 node-coap 库吗?

c# - 在 .NET 的 Win Form 中嵌入不同的应用程序

c# - 为什么 IDictionary<TKey,TValue> 不/不能实现 ILookup<TKey,TValue>?

c# - 在C#中对应用程序的UI进行完全改写后,现有按钮及其功能停止工作

c# - 在每个请求上验证 OpenId IdToken

python - 有什么方法可以将 Scapy Packet 中的字段链接到构建的 str 中的部分吗?