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

时间:2018-10-08 08:19:01

标签: 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地址。

1 个答案:

答案 0 :(得分:2)

显然,该IP地址位于exchange.Request.Source.ToString()下。如果您是从localhost而不是127.0.0.1发送一个程序包,它将仅显示localhost并使其更难找到。

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

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

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