本文简要说明coap URI构成及URI到option的处理方式

概述 链接到标题

coap URI用于识别coap资源和提供定位资源的方法, coap的资源按照层次结构组织,并由coap服务器管理。coap提供coap://和coaps://两种URI类型,本文已coap://为例进行说明。名说明响应option

URI 构成 (URI Scheme) 链接到标题

coap-URI = “coap:” “//” host [ “:” port ] path-abempty [ “?” query ] 例如

coap://192.0.2.1/test
coap://192.0.2.1:5687/test
coap://myhome/env/sensor/?name=temperature
coap://myhome/env/sensor/?name=temperature&room=bedroom
  • host : 不能为空,如果host给的是ip地址就直接访问,如果给的是host name则要通过DNS解析
  • port : 可选,如果不写,coap默认是5683端口,coaps是5684
  • path-abempty :可以为空,或者是以/开始的路径
  • “?” query : 查询以?开始,并接着key=value,如果有多个query用&连接

由于coap使用的资源通常受限,因此实际应用开发的时候coap劲量使用短的URI

URI to option 链接到标题

通常情况下coap的URI会被分解并放在coap的网络封包的option内,对应的option有4种:Uri-Host,Uri-Port,Uri-Path,Uri-Query

转换规则 链接到标题

Uri-Host 链接到标题

如果host是ip地址,无该option。如果host不是ip地址,则有Uri-Host选项,内容为host的小写ASCII码的percent-encoding

Uri-Port 链接到标题

如果URI内有port但不是10机制数,则使用默认端口. 如果port号和目的端口号不相等,则有Uri-Port,内容为port号

Uri-Path 链接到标题

当path-abempty不为空时,path-abempty每个段都进行percent-encoding,并对应一个Uri-Path。因此可能出现多个Uri-Path option

Uri-Query 链接到标题

query中每一个参数都转换为percent-encoding,并对应一个Uri-Query,因此可能出现多个Uri-Query option 转换时去掉?和分隔号&

Option说明 链接到标题

Uri-Host 链接到标题

option no: 3 format: string length: 1~255 default: 请求目标地址IP

Uri-Port 链接到标题

option no: 7 format: uint length: 0~2 default: 请求目标地址port

Uri-Path 链接到标题

option no: 11 format: string length: 0~255 default: none

Uri-Path 链接到标题

option no: 15 format: string length: 0~255 default: none

示例 链接到标题

示例1 链接到标题

Input:
    Destination IP Address = 192.0.2.1
    Destination UDP Port = 5683
    Uri-Host = "example.net"
    Uri-Path = ".well-known"
    Uri-Path = "core"

Output:
    coap://example.net/.well-known/core

示例2 链接到标题

GET: 
    coap://192.0.2.1/seg1/seg2/seg3

option:
    Uri-Host = "192.0.2.1"
    Uri-Port = 5683
    Uri-Path = "seg1"
    Uri-Path = "seg2"
    Uri-Path = "seg3"

wireshark分析如下图: uri

题外话 链接到标题

percent-encoding:百分号编码也称作URL编码, 是特定的编码机制,由RFC 3986规定其标准,大体分为以下,详细见参考文件

  • 保留字符: 先转为UTF8字节序,然后对字节值进行百分号编码
  • 未保留字符: 不进行百分号编码

参考 链接到标题

https://tools.ietf.org/html/rfc7252 https://tools.ietf.org/html/rfc3986#section-2.1