學習UPnP


轉自:http://blog.csdn.net/ohatn/article/details/6255488

UPnP(Universal plug-and-play 即通用即插即用)是由通用即插即用論壇 (UPnP™ Forum)提出的一套網絡協議。該協議的目標是使家庭網絡(數據共享、通信和娛樂)和公司網絡中的各種設備能夠相互無縫連接,並簡化相關網絡的實現。 UPnP 通過定義和發布基於開放、因特網通訊網協議標准的 UPnP 設備控制協議來實現這一目標。
簡單地理解,UPnP就是一種動態端口映射。
詳細一點說,假設內網某台機器連接的網關設備支持 UPNP igd 接口並開啟了此項功能,那么網關設備就能夠響應內網機器的請求,執行一些和網關相關的操作,比如將內網機器的某個端口映射到外網某個固定端口(即 NAT)。這樣就能夠使外網能夠直接訪問到內網機器的某端口。

那么,UPnP應用在什么地方呢?
我們比較熟悉的eMule、BitComet等工具,就使用了UPnP,所以我們可以通過打開ADSL的UPnP來提高下載速度。
更遠一些的應用前景可能在數字家電上。支持UPnP的數字家電,在得到用戶的授權后,能夠自動到家中的網關上開啟端口映射,這樣用戶就可以在外網對家中的家電進行控制。

下面簡單介紹一下UPnP端口映射的過程和簡單原理:
(下面文章中的控制點表示內網中的機器)

第0步:尋址,即獲取一個本地IP地址。

第1步:發現,即搜索網絡中的UPnP設備。又分兩個小的步驟。
第1.1步:搜索UPnP設備。
控制點生成一個UDP的MulticastSocket,綁定多播地址239.255.255.250 1900端口,然后發送一個搜索請求,該請求在UPnP Device Architecture中的定義如下:
    M-SEARCH * HTTP/1.1
    HOST:239.255.255.250:1900
    MAN:"ssdp:discover"
    MX:seconds to delay response
    ST:search target

這個多播請求的含義如下:
M-SEARCH表示SSDP協議定義的搜索請求方法。
HOST的值必須是這個地址。
MAN的值必須是"ssdp:discover",注意不能少了雙引號。
MX的表示UPnP設備收到該請求后的延時時間,以便控制點能夠處理請求。
ST表示搜索目標,
  如果搜索所有的設備和服務,則為ssdp:all,
  如果是搜索根設備,則為upnp:rootdevice,
  象大部分程序中使用UPnP是為了找到支持UPnP的網關來動態映射端口,
  則賦值為urn:schemas-upnp-org:device:InternetGatewayDevice:1。
另外在編程時需要在每一行后面加上"/r/n" 表示換行。
該請求基於HTTPMU(HTTP Multicast over UDP),上面這些信息都是屬於HTTP Header,沒有HTTP Body,而HTTP Header和HTTP Body之間應該有一個空行分隔。編寫時需要注意不能少了那個空行。

第1.2步:網絡上的UPnP設備返回響應。如果該UPnP設備和要搜索的UPnP設備匹配,則該設備會返回一個響應,響應的格式在UPnP Device Architecture中的定義如下:
    HTTP/1.1 200 OK
    CACHE-CONTROL: max-age = seconds until advertisement expires
    DATE: when response was generated
    EXT:
    LOCATION: URL for UPnP description for root device
    SERVER: OS/version UPnP/1.0 product/version
    ST: search target
    USN: advertisement UUID

max-age通知消息存活時間,如果超過此時間間隔,控制點可以認為設備不存在。
LOCATION表示該設備的描述文件,用於確定該設備包含哪些邏輯設備和哪些服務等。
其中包含設備描述的URL地址。
USN表示Unique Service Name。

接收到數據包后,就要從中獲取需要的消息。
首先,必須找到"200 OK"。
接着,要找到LOCATION項,並從中獲得設備描述URL。
這一部分的邏輯實際上就是一個子字符串的查找。

第2步:描述,得到UPnP設備屬性和描述信息。
第2.1步:下載設備描述文件。
  2.1.1 解析描述文件的URL,獲取主機/端口/路徑;
  2.1.2 建立TCP連接到host:post;
  2.1.3 構造類似
    GET path HTTP/1.1
    Host: host:port

  的信息(注意第二行下面要有一個空行),並發送到設備;
  2.1.4 接收設備響應的數據。

第2.2步:解析XML文件。
設備響應的格式在UPnP Device Architecture中的定義如下:
<?xml version="1.0"?>
<root xmlns="urn:schemas-upnp-org:device-1-0">
  <specVersion>
    <major>1</major>
    <minor>0</minor>
  </specVersion>
  <URLBase>base URL for all relative URLs</URLBase>
  <device>
    <deviceType>urn:schemas-upnp-org:device:deviceType:v </deviceType>
    <friendlyName>short user-friendly title</friendlyName>
    <manufacturer>manufacturer name</manufacturer>
    <manufacturerURL>URL to manufacturer site</manufacturerURL>
    <modelDescription>long user-friendly title</modelDescription>
    <modelName>model name</modelName>
    <modelNumber>model number</modelNumber>
    <modelURL>URL to model site</modelURL>
    <serialNumber>manufacturer's serial number</serialNumber>
    <UDN>uuid:UUID</UDN>
    <UPC>Universal Product Code</UPC>
    <iconList>
      <icon>
        <mimetype>image/format</mimetype>
        <width>horizontal pixels</width>
        <height>vertical pixels</height>
        <depth>color depth</depth>
        <url>URL to icon</url>
      </icon>
      XML to declare other icons, if any, go here
    </iconList>
    <serviceList>
      <service>
        <serviceType>urn:schemas-upnp-org:service:serviceType:v </serviceType>
        <serviceId>urn:upnp-org:serviceId:serviceID </serviceId>
        <SCPDURL>URL to service description</SCPDURL>
        <controlURL>URL for control</controlURL>
        <eventSubURL>URL for eventing</eventSubURL>
      </service>
      Declarations for other services defined by a UPnP Forum working committee (if any) go here
      Declarations for other services added by UPnP vendor (if any) go here
    </serviceList>
    <deviceList>
      Description of embedded devices defined by a UPnP Forum working committee (if any) go here
      Description of embedded devices added by UPnP vendor (if any) go here
    </deviceList>
    <presentationURL>URL for presentation</presentationURL>
  </device>
</root>

上面的設備描述中有一個ServiceList節點,該節點下每個Service節點都包含一個controlURL節點,但這個URL是一個相對URL,再組合URLBase節點的屬性值,即得到該服務的控制URL。

第3步:控制,對UPnP設備發送控制命令(如增刪端口映射)或查詢屬性。
這個操作是通過發送相應SOAP消息到該服務的控制URL上來完成的。該信息在UPnP Device Architecture中的定義如下:
    POST path of control URL HTTP/1.1
    HOST: host of control URL :port of control URL
    CONTENT-LENGTH: bytes in body
    CONTENT-TYPE: text/xml; charset="utf-8"
    SOAPACTION: "urn:schemas-upnp-org:service:serviceType:v #actionName "

    <s:Envelope
        xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
        s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <s:Body>
        <u:actionName xmlns:u="urn:schemas-upnp-org:service:serviceType:v ">
          <argumentName >in arg value</argumentName >
          other in args and their values go here, if any
        </u:actionName >
      </s:Body>
    </s:Envelope>
在上面的SOAP消息中:
在actionName處填入各種控制信息,如:
AddPortMapping
或者DeletePortMapping
或者GetGenericPortMappingEntry。
在serviceType處填入設備的服務類型,如:
urn:schemas-upnp-org:service:WANIPConnection:1
或者urn:schemas-upnp-org:service:WANPPPConnection:1。
在 argumentName 處填入各種控制信息,各種控制消息的格式如下:
增加端口映射AddPortMapping:
  <NewRemoteHost></NewRemoteHost>
  <NewExternalPort>ExternalPort</NewExternalPort>
  <NewProtocol>Protocol</NewProtocol>
  <NewInternalPort>InternalPort</NewInternalPort>
  <NewInternalClient>InternalClient</NewInternalClient>
  <NewEnabled>1</NewEnabled>
  <NewPortMappingDescription>PortMappingDescription</NewPortMappingDescription>
  <NewLeaseDuration>LeaseDuration</NewLeaseDuration>

注:Protocol 一般填TCP或UDP。
    PortMappingDescription 填寫端口映射的描述,比如什么程序建立了這個端口。
    InternalClient 填寫本地IP地址。
    LeaseDuration 填寫映射的持續時間,用0表示不永久。

刪除端口映射DeletePortMapping:
  <NewRemoteHost></NewRemoteHost>
  <NewExternalPort>ExternalPort</NewExternalPort>
  <NewProtocol>Protocol</NewProtocol>
獲得端口映射信息GetGenericPortMappingEntry:
  <NewPortMappingIndex>PortMappingIndex</NewPortMappingIndex>
  <NewRemoteHost></NewRemoteHost>
  <NewExternalPort></NewExternalPort>
  <NewProtocol></NewProtocol>
  <NewInternalPort></NewInternalPort>
  <NewInternalClient></NewInternalClient>
  <NewEnabled>1</NewEnabled>
  <NewPortMappingDescription></NewPortMappingDescription>
  <NewLeaseDuration></NewLeaseDuration>

注: PortMappingIndex 填寫端口映射索引,即路由上第幾個映射。

以在IGD設備上增加端口映射這個操作來舉例,將網關的5678端口映射到內網10.0.0.1的8765端口,該操作被發送的SOAP消息如下:
    POST /upnp/control/wanpppcpppoe HTTP/1.0
    CONTENT-TYPE: text/xml; charset="utf-8"
    HOST: 10.0.0.138:80
    CONTENT-LENGTH: 649
    SOAPACTION: "urn:schemas-upnp-org:service:WANPPPConnection:1#AddPortMapping"
    
    <?xml version="1.0" encoding="utf-8"?>
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
     <s:Body>
      <u:AddPortMapping xmlns:u="urn:schemas-upnp-org:service:WANPPPConnection:1">
       <NewRemoteHost></NewRemoteHost>
       <NewExternalPort>5678</NewExternalPort>
       <NewProtocol>tcp</NewProtocol>
       <NewInternalPort>8765</NewInternalPort>
       <NewInternalClient>10.0.0.1</NewInternalClient>
       <NewEnabled></NewEnabled>
       <NewPortMappingDescription></NewPortMappingDescription>
       <NewLeaseDuration></NewLeaseDuration>
      </u:AddPortMapping>
     </s:Body>
    </s:Envelope>
操作成功,設備的應答是:
    HTTP/1.0 200 OK
    CONTENT-TYPE: text/xml; charset="utf-8"
    SERVER: SpeedTouch 510 4.0.2.0.1 UPnP/1.0 (14E31Y7)
    CONTENT-LENGTH: 304
    Connection: close
    EXT:
    
    <?xml version="1.0"?>
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <s:Body>
        <m:AddPortMappingResponse xmlns:m="urn:schemas-upnp-org:service:WANPPPConnection:1"></m:AddPortMappingResponse>
      </s:Body>
    </s:Envelope>
接收到應答后,一般檢測到“200 OK”即可認為成功。

第4步:事件觸發。在設備一些屬性變化了的時候,如果控制點訂閱了它的事件通知,則它會發送相應的通知給控制點。

第5步:展示。

UPnP Device Architecture的翻譯版可以在CSDN資源中找,名為UPnP設備架構。

以上文章取自網上多篇文章,在此表示感謝。

相關鏈接:
http://www.upnp.org/download/UPnPDA10_20000613.htm
http://blog.csdn.net/motiandashao/archive/2007/03/30/1547184.aspx
http://hi.baidu.com/neron/blog/item/8a7db81e136d2617403417d9.html/cmtid/02b0ec1fd579d56ef724e410


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM