在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地址是在交换下找到的。Request.Source.ToString((.如果您从本地主机而不是 127.0.0.1 发送包,它只会说本地主机,使其更难找到。
"Uri uri = new Uri("coap://localhost:" + _port + "/" + "Test");"
编辑:另外,也许对于未来需要这个的人:如果你只需要IP地址或端口,不要拆分交换。Request.Source. Visual Studio 自动解析交换。请求源到终结点。这应该是 IPEndpoint 而不是终结点,因为如果它是终结点,则会丢失"地址"和"端口"属性。您可以像这样修复它:
if (exchange.Request.Source is IPEndPoint p)
{
//p.Address
//p.Port
}
else
{
//Handle errors here
}