【发布时间】:2018-10-08 08:19:01
【问题描述】:
在 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 地址。
【问题讨论】:
-
你检查
exchange.Request的属性了吗? -
是的。我没有看到任何包含发件人 IP 地址的属性。
-
Request的Host属性怎么样?你检查了吗? -
我查过了,但我现在找到了。显然,IP 地址在 Exchange.Request.Source.ToString(); 下。我会回答这个问题并自己解决。无论如何谢谢!我首先没有找到它,因为我从 localhost 而不是 127.0.0.1 发送了一个包。