在C#中,我试图获取CoAP客户端的IP地址。这有可能吗?我尝试过查看我收到的exchange对象,但是我似乎找不到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地址。我试过检查exchange对象中的所有属性,但似乎找不到我可以使用的IP地址。
发布于 2018-10-08 08:54:36
显然,IP地址是在exchange.Request.Source.ToString()下面找到的。如果您从localhost (而不是127.0.0.1 )发送一个包,它只会说localhost,因此很难找到它。
"Uri uri = new Uri("coap://localhost:" + _port + "/" + "Test");"编辑:同样,对于未来需要这样做的人来说:如果你只需要IP地址或端口,不要分割exchange.Request.Source。Visual自动生成exchange.Request.Source到端点。这应该是IPEndpoint,而不是端点,因为如果它是端点,则会丢失"Address“和"Port”属性。你可以这样修正它:
if (exchange.Request.Source is IPEndPoint p)
{
//p.Address
//p.Port
}
else
{
//Handle errors here
}https://stackoverflow.com/questions/52698094
复制相似问题