LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 实现uPnP映射

admin
2021年2月2日 17:42 本文热度 3588

     上网找了很多关于C# 实现uPnP映射的资料,好用的资料不是很多,很多人都是用系统UPnP.dll封装好的方法,但是我在vs2010下用C#尝试不是很成功。很多时候UPnPNATClass nat=new UPnPNATClass();得到的都是null值.终于找到了一个自己封装SOAP进行uPnP端口映射的方法,我帮作者把类又重新封装了一下。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Xml;

  1. public sealed class upnpLib
  2. {
  3. public enum InternetConnectTypes { IPv4, IPv6 }
  4. public enum ResultTypes { Success, Faild }
  5. public class RootDevice
  6. {
  7. #region -- Private Fields --
  8. private string _location;
  9. private string _host;
  10. private string _port;
  11. private string _server;
  12. private int _maxAge;
  13. public string _USN;
  14. #endregion
  15. #region -- Properties --
  16. public string Location
  17. {
  18. get { return this._location; }
  19. set { this._location = value; }
  20. }
  21. public string Host
  22. {
  23. get { return this._host; }
  24. set { this._host = value; }
  25. }
  26. public string Port
  27. {
  28. get { return this._port; }
  29. set { this._port = value; }
  30. }
  31. public string Server
  32. {
  33. get { return this._server; }
  34. set { this._server = value; }
  35. }
  36. public int MaxAge
  37. {
  38. get { return this._maxAge; }
  39. set { this._maxAge = value; }
  40. }
  41. public string USN
  42. {
  43. get { return this._USN; }
  44. set { this._USN = value; }
  45. }
  46. #endregion
  47. #region -- Method --
  48. public RootDevice(string location)
  49. {
  50. this.Host = location.Substring(location.IndexOf(''/'') + 2, location.IndexOf(''/'', location.IndexOf(''/'') + 2) - (location.IndexOf(''/'') + 2));
  51. this.Port = this.Host.Substring(this.Host.IndexOf('':'') + 1);
  52. this.Host = this.Host.Substring(0, this.Host.IndexOf('':''));
  53. this.Location = location.Substring(location.IndexOf(''/'', location.IndexOf(''/'') + 2));
  54. }
  55. #endregion
  56. }
  57. public class DeviceService
  58. {
  59. #region -- Private Fields --
  60. private string _type;
  61. private string _id;
  62. private string _scpdUrl;
  63. private string _controlUrl;
  64. private string _eventSubUrl;
  65. private string _baseUrl;
  66. #endregion
  67. #region -- Properties --
  68. public string Type
  69. {
  70. get { return this._type; }
  71. set { this._type = value; }
  72. }
  73. public string ID
  74. {
  75. get { return this._id; }
  76. set { this._id = value; }
  77. }
  78. public string SCPDUrl
  79. {
  80. get { return this._scpdUrl; }
  81. set { this._scpdUrl = value; }
  82. }
  83. public string ControlUrl
  84. {
  85. get { return this._controlUrl; }
  86. set { this._controlUrl = value; }
  87. }
  88. public string EventSubUrl
  89. {
  90. get { return this._eventSubUrl; }
  91. set { this._eventSubUrl = value; }
  92. }
  93. public string BaseUrl
  94. {
  95. get { return this._baseUrl; }
  96. set { this._baseUrl = value; }
  97. }
  98. #endregion
  99. }
  100. public class ServicePoint
  101. {
  102. #region -- Private Fields --
  103. private string _name;
  104. private IList<Argument> _argumentList = new List<Argument>();
  105. #endregion
  106. #region -- Properties --
  107. public string Name
  108. {
  109. get { return this._name; }
  110. set { this._name = value; }
  111. }
  112. public IList<Argument> ArgumentList
  113. {
  114. get { return this._argumentList; }
  115. set { this._argumentList = value; }
  116. }
  117. #endregion
  118. }
  119. public class Argument
  120. {
  121. #region -- Private Fields --
  122. private string _name;
  123. private string _direction;
  124. private string _relatedStateVariable;
  125. #endregion
  126. #region -- Properties --
  127. public string Name
  128. {
  129. get { return this._name; }
  130. set { this._name = value; }
  131. }
  132. public string Direction
  133. {
  134. get { return this._direction; }
  135. set { this._direction = value; }
  136. }
  137. public string RelatedStateVariable
  138. {
  139. get { return this._relatedStateVariable; }
  140. set { this._relatedStateVariable = value; }
  141. }
  142. #endregion
  143. }
  144. public class StateVariable
  145. {
  146. #region -- Private Fields --
  147. private string _sendEvents;
  148. private string _name;
  149. private string _dataType;
  150. private IList<string> _allowedValueList = new List<string>();
  151. #endregion
  152. #region -- Properties --
  153. public string SendEvents
  154. {
  155. get { return this._sendEvents; }
  156. set { this._sendEvents = value; }
  157. }
  158. public string Name
  159. {
  160. get { return this._name; }
  161. set { this._name = value; }
  162. }
  163. public string DataType
  164. {
  165. get { return this._dataType; }
  166. set { this._dataType = value; }
  167. }
  168. public IList<string> AllowedValueList
  169. {
  170. get { return this._allowedValueList; }
  171. set { this._allowedValueList = value; }
  172. }
  173. #endregion
  174. }
  175. public class Result
  176. {
  177. #region -- Private Fields--
  178. private ResultTypes _status;
  179. private string _message;
  180. #endregion
  181. #region -- Properties --
  182. public ResultTypes Status
  183. {
  184. get { return this._status; }
  185. set { this._status = value; }
  186. }
  187. public string Message
  188. {
  189. get { return this._message; }
  190. set { this._message = value; }
  191. }
  192. #endregion
  193. }
  194. #region -- Private Fields --
  195. private InternetConnectTypes _ict;
  196. private Result r = new Result();
  197. private DeviceService service = null;
  198. private IList<RootDevice> devices = null;
  199. private IList<DeviceService> services = null;
  200. private IList<ServicePoint> _actions = null;
  201. private IList<StateVariable> _stateVariables = null;
  202. #endregion
  203. #region -- Properties --
  204. public InternetConnectTypes InternetConnectType
  205. {
  206. get { return this._ict; }
  207. set { this._ict = value; }
  208. }
  209. public IList<ServicePoint> ActionList
  210. {
  211. get { return this._actions; }
  212. }
  213. public IList<StateVariable> StateVariableList
  214. {
  215. get { return this._stateVariables; }
  216. }
  217. #endregion
  218. #region -- Method --
  219. public upnpLib(InternetConnectTypes ict)
  220. {
  221. this.InternetConnectType = ict;
  222. r.Status = ResultTypes.Success;
  223. try
  224. {
  225. this.devices = this.discoverDevices(5);
  226. if (this.devices.Count == 0)
  227. {
  228. throw new Exception("没有发现可用uPnP设备!");
  229. }
  230. this.services = this.getDeviceSvc(this.getDeviceDesc(this.devices[0]));
  231. foreach (DeviceService s in this.services)
  232. {
  233. if (s.Type.Contains("service:WANIPConnection"))
  234. {
  235. this.service = s;
  236. string Xml = this.getServiceDesc(this.devices[0],s);
  237. this._actions = this.getServicePoint(Xml);
  238. this._stateVariables = this.GetStateVariables(Xml);
  239. break;
  240. }
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. r.Status = ResultTypes.Faild;
  246. r.Message = ex.Message;
  247. }
  248. }
  249. private IList<RootDevice> discoverDevices(int timeOut)
  250. {
  251. #region -- Send UDP data --
  252. string strData = "M-SEARCH * HTTP/1.1\r\n" +
  253. "HOST: 239.255.255.250:1900\r\n" +
  254. "MAN:\"ssdp:discover\"\r\n" +
  255. "MX:" + timeOut.ToString() + "\r\n" +
  256. "ST:upnp:rootdevice\r\n\r\n";
  257. byte[] data = Encoding.UTF8.GetBytes(strData);
  258. UdpClient uc = new UdpClient(this.InternetConnectType == InternetConnectTypes.IPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6);
  259. IPEndPoint IPep = new IPEndPoint(IPAddress.Broadcast, 1900);
  260. uc.Send(data, data.Length, IPep);
  261. Timer RecvTimeOut = new Timer(this.RecvTimeOutFunc, uc, timeOut * 1000, timeOut * 1000);
  262. IList<RootDevice> hints = new List<RootDevice>();
  263. #endregion
  264. #region -- Recive response --
  265. byte[] buffer = null;
  266. int start, end;
  267. string temp = "", find = "";
  268. RootDevice hint;
  269. while (buffer == null || buffer.Length == 0)
  270. {
  271. buffer = uc.Receive(ref IPep);
  272. if (buffer != null && buffer.Length > 0)
  273. {
  274. strData = Encoding.UTF8.GetString(buffer);
  275. if (!strData.Contains("upnp:rootdevice")) continue;
  276. // Location
  277. temp = "";find = "LOCATION:";
  278. start = strData.IndexOf(find);
  279. if (start > -1)
  280. {
  281. end = strData.IndexOf("\r\n", start);
  282. temp = strData.Substring(start + find.Length, end - (start + find.Length)).Trim();
  283. hint = new RootDevice(temp);
  284. }
  285. else
  286. {
  287. continue;
  288. }
  289. // Max age
  290. temp = ""; find = "max-age =";
  291. start = strData.IndexOf(find);
  292. if (start > -1)
  293. {
  294. end = strData.IndexOf("\r\n", start);
  295. temp = strData.Substring(start + find.Length, end - (start + find.Length)).Trim();
  296. hint.MaxAge = int.Parse(temp);
  297. }
  298. else
  299. {
  300. continue;
  301. }
  302. // Server
  303. temp = ""; find = "SERVER:";
  304. start = strData.IndexOf(find);
  305. if (start > -1)
  306. {
  307. end = strData.IndexOf("\r\n", start);
  308. temp = strData.Substring(start + find.Length, end - (start + find.Length)).Trim();
  309. hint.Server = temp;
  310. }
  311. else
  312. {
  313. continue;
  314. }
  315. // USN
  316. temp = ""; find = "USN:";
  317. start = strData.IndexOf(find);
  318. if (start > -1)
  319. {
  320. end = strData.IndexOf("\r\n", start);
  321. temp = strData.Substring(start + find.Length, end - (start + find.Length)).Trim();
  322. hint.USN = temp;
  323. }
  324. else
  325. {
  326. continue;
  327. }
  328. hints.Add(hint);
  329. break;
  330. }
  331. }
  332. #endregion
  333. uc.Close();
  334. return hints;
  335. }
  336. private void RecvTimeOutFunc(object uc)
  337. {
  338. ((UdpClient)uc).Close();
  339. }
  340. private string getDeviceDesc(RootDevice rd)
  341. {
  342. string strData = "GET " + rd.Location + " HTTP/1.1\r\n" +
  343. "HOST:" + rd.Host + ":" + rd.Port + "\r\n" +
  344. "ACCEPT-LANGUAGE: \r\n\r\n", result = "";
  345. byte[] data = Encoding.UTF8.GetBytes(strData);
  346. IPAddress ipadr = (Dns.GetHostAddresses(rd.Host))[0];
  347. IPEndPoint IPep = new IPEndPoint(ipadr, int.Parse(rd.Port));
  348. TcpClient tc = new TcpClient(this.InternetConnectType == InternetConnectTypes.IPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6);
  349. NetworkStream ns = null;
  350. try
  351. {
  352. tc.Connect(IPep);
  353. ns = tc.GetStream();
  354. ns.Write(data, 0, data.Length);
  355. Thread.Sleep(100);
  356. int ReadSize = 2048;
  357. byte[] buff = new byte[ReadSize], readBuff;
  358. strData = "";
  359. while (ReadSize == 2048)
  360. {
  361. ReadSize = ns.Read(buff, 0, buff.Length);
  362. readBuff = new byte[ReadSize];
  363. Array.Copy(buff, 0, readBuff, 0, ReadSize);
  364. strData += Encoding.UTF8.GetString(readBuff);
  365. }
  366. result = strData.Substring(strData.IndexOf("\r\n\r\n") + 4).Trim();
  367. while (result.Substring(result.Length - 2) == "\r\n" || result.Substring(result.Length - 2) == Encoding.Default.GetString(new byte[2] { 0, 0 }))
  368. {
  369. result = result.Substring(0, result.Length - 2);
  370. }
  371. }
  372. catch { }
  373. finally
  374. {
  375. if (ns != null)
  376. {
  377. ns.Close();
  378. ns.Dispose();
  379. }
  380. if (tc != null)
  381. {
  382. tc.Close();
  383. }
  384. }
  385. return result;
  386. }
  387. private IList<DeviceService> getDeviceSvc(string Xml)
  388. {
  389. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Xml));
  390. XmlReader xr = XmlReader.Create(ms);
  391. IList<DeviceService> hints = new List<DeviceService>();
  392. string URLBase = "";
  393. while (xr.Read())
  394. {
  395. if (xr.NodeType == XmlNodeType.Element && xr.Name == "URLBase")
  396. {
  397. do
  398. {
  399. xr.Read();
  400. if (xr.NodeType == XmlNodeType.Text)
  401. {
  402. URLBase = xr.Value;
  403. }
  404. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "URLBase");
  405. continue;
  406. }
  407. if (xr.NodeType == XmlNodeType.Element && xr.Name == "service")
  408. {
  409. DeviceService s = new DeviceService();
  410. s.BaseUrl = URLBase;
  411. string curElement = string.Empty;
  412. do
  413. {
  414. xr.Read();
  415. if (xr.NodeType == XmlNodeType.Element)
  416. {
  417. curElement = xr.Name;
  418. continue;
  419. }
  420. if (xr.NodeType == XmlNodeType.EndElement)
  421. {
  422. curElement = null;
  423. continue;
  424. }
  425. if (xr.NodeType == XmlNodeType.Text)
  426. {
  427. switch (curElement)
  428. {
  429. case "serviceType":
  430. s.Type = xr.Value;
  431. break;
  432. case "serviceId":
  433. s.ID = xr.Value;
  434. break;
  435. case "SCPDURL":
  436. s.SCPDUrl = xr.Value;
  437. break;
  438. case "controlURL":
  439. s.ControlUrl = xr.Value;
  440. break;
  441. case "eventSubURL":
  442. s.EventSubUrl = xr.Value;
  443. break;
  444. default:
  445. break;
  446. };
  447. }
  448. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "service");
  449. hints.Add(s);
  450. }
  451. }
  452. return hints;
  453. }
  454. private string getServiceDesc(RootDevice rd, DeviceService ds)
  455. {
  456. string strData = "GET " + ds.BaseUrl + ds.SCPDUrl + " HTTP/1.1\r\n" +
  457. "HOST:" + rd.Host + ":" + rd.Port + "\r\n" +
  458. "ACCEPT-LANGUAGE: \r\n\r\n", result = "";
  459. byte[] data = Encoding.UTF8.GetBytes(strData);
  460. IPAddress ipadr = (Dns.GetHostAddresses(rd.Host))[0];
  461. IPEndPoint IPep = new IPEndPoint(ipadr, int.Parse(rd.Port));
  462. TcpClient tc = new TcpClient(this.InternetConnectType == InternetConnectTypes.IPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6);
  463. NetworkStream ns = null;
  464. try
  465. {
  466. tc.Connect(IPep);
  467. ns = tc.GetStream();
  468. ns.Write(data, 0, data.Length);
  469. Thread.Sleep(100);
  470. int ReadSize = 2048;
  471. byte[] buff = new byte[ReadSize], readBuff;
  472. strData = "";
  473. while (ReadSize == 2048)
  474. {
  475. ReadSize = ns.Read(buff, 0, buff.Length);
  476. readBuff = new byte[ReadSize];
  477. Array.Copy(buff, 0, readBuff, 0, ReadSize);
  478. strData += Encoding.UTF8.GetString(readBuff);
  479. }
  480. result = strData.Substring(strData.IndexOf("\r\n\r\n") + 4).Trim();
  481. while (result.Substring(result.Length - 2) == "\r\n" || result.Substring(result.Length - 2) == Encoding.Default.GetString(new byte[2] { 0, 0 }))
  482. {
  483. result = result.Substring(0, result.Length - 2);
  484. }
  485. }
  486. catch { }
  487. finally
  488. {
  489. if (ns != null)
  490. {
  491. ns.Close();
  492. ns.Dispose();
  493. }
  494. if (tc != null)
  495. {
  496. tc.Close();
  497. }
  498. }
  499. return result;
  500. }
  501. private IList<ServicePoint> getServicePoint(string Xml)
  502. {
  503. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Xml));
  504. XmlReader xr = XmlReader.Create(ms);
  505. IList<ServicePoint> hints = new List<ServicePoint>();
  506. while (xr.Read())
  507. {
  508. if (xr.NodeType == XmlNodeType.Element && xr.Name == "action")
  509. {
  510. ServicePoint sp = new ServicePoint();
  511. string curElement = string.Empty;
  512. do
  513. {
  514. xr.Read();
  515. if (xr.NodeType == XmlNodeType.Element && xr.Name != "argumentList")
  516. {
  517. curElement = xr.Name;
  518. continue;
  519. }
  520. if (xr.NodeType == XmlNodeType.EndElement && xr.Name != "argumentList")
  521. {
  522. curElement = null;
  523. continue;
  524. }
  525. if (xr.NodeType == XmlNodeType.Text)
  526. {
  527. switch (curElement)
  528. {
  529. case "name":
  530. sp.Name = xr.Value;
  531. break;
  532. default:
  533. break;
  534. };
  535. continue;
  536. }
  537. if (xr.NodeType == XmlNodeType.Element && xr.Name == "argumentList")
  538. {
  539. string curElement2 = string.Empty;
  540. do
  541. {
  542. xr.Read();
  543. if (xr.NodeType == XmlNodeType.Element && xr.Name == "argument")
  544. {
  545. Argument arg = new Argument();
  546. do
  547. {
  548. xr.Read();
  549. if (xr.NodeType == XmlNodeType.Element)
  550. {
  551. curElement2 = xr.Name;
  552. continue;
  553. }
  554. if (xr.NodeType == XmlNodeType.EndElement)
  555. {
  556. curElement2 = null;
  557. continue;
  558. }
  559. if (xr.NodeType == XmlNodeType.Text)
  560. {
  561. switch (curElement2)
  562. {
  563. case "name":
  564. arg.Name = xr.Value;
  565. break;
  566. case "direction":
  567. arg.Direction = xr.Value;
  568. break;
  569. case "relatedStateVariable":
  570. arg.RelatedStateVariable = xr.Value;
  571. break;
  572. default:
  573. break;
  574. };
  575. }
  576. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "argument");
  577. sp.ArgumentList.Add(arg);
  578. }
  579. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "argumentList");
  580. }
  581. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "action");
  582. hints.Add(sp);
  583. }
  584. }
  585. return hints;
  586. }
  587. private IList<StateVariable> GetStateVariables(string Xml)
  588. {
  589. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Xml));
  590. XmlReader xr = XmlReader.Create(ms);
  591. IList<StateVariable> hints = new List<StateVariable>();
  592. while (xr.Read())
  593. {
  594. if (xr.NodeType == XmlNodeType.Element && xr.Name == "stateVariable")
  595. {
  596. StateVariable hint = new StateVariable();
  597. hint.SendEvents = xr.GetAttribute("sendEvents");
  598. string curElement = string.Empty;
  599. do
  600. {
  601. xr.Read();
  602. if (xr.NodeType == XmlNodeType.Element && xr.Name != "allowedValueList")
  603. {
  604. curElement = xr.Name;
  605. continue;
  606. }
  607. if (xr.NodeType == XmlNodeType.EndElement && xr.Name != "allowedValueList")
  608. {
  609. curElement = null;
  610. continue;
  611. }
  612. if (xr.NodeType == XmlNodeType.Text)
  613. {
  614. switch (curElement)
  615. {
  616. case "name":
  617. hint.Name = xr.Value;
  618. break;
  619. case "dataType":
  620. hint.DataType = xr.Value;
  621. break;
  622. default:
  623. break;
  624. };
  625. continue;
  626. }
  627. if (xr.NodeType == XmlNodeType.Element && xr.Name == "allowedValueList")
  628. {
  629. string curElement2 = string.Empty;
  630. do
  631. {
  632. xr.Read();
  633. if (xr.NodeType == XmlNodeType.Element)
  634. {
  635. curElement2 = xr.Name;
  636. continue;
  637. }
  638. if (xr.NodeType == XmlNodeType.EndElement)
  639. {
  640. curElement2 = null;
  641. continue;
  642. }
  643. if (xr.NodeType == XmlNodeType.Text)
  644. {
  645. switch (curElement2)
  646. {
  647. case "allowedValue":
  648. hint.AllowedValueList.Add(xr.Value);
  649. break;
  650. default:
  651. break;
  652. };
  653. }
  654. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "allowedValueList");
  655. }
  656. } while (xr.NodeType != XmlNodeType.EndElement || xr.Name != "stateVariable");
  657. hints.Add(hint);
  658. }
  659. }
  660. return hints;
  661. }
  662. private void makeAddPortMappingSOAP(RootDevice dev, DeviceService srv, string NewRemoteHost, string NewExternalPort, string NewProtocol, string NewInternalPort, string NewPortMappingDescription, string NewLeaseDuration)
  663. {
  664. string InternalAddress = string.Empty;
  665. IPAddress[] addrs = Dns.GetHostAddresses(Dns.GetHostName());
  666. foreach (IPAddress addr in addrs)
  667. {
  668. if (addr.AddressFamily == AddressFamily.InterNetwork)
  669. {
  670. InternalAddress = addr.ToString();
  671. }
  672. }
  673. string strData = "<u:AddPortMapping xmlns:u=\"" + srv.Type + "\">" +
  674. "<NewRemoteHost></NewRemoteHost>" +
  675. "<NewExternalPort>" + NewExternalPort + "</NewExternalPort>" +
  676. "<NewProtocol>" + NewProtocol + "</NewProtocol>" +
  677. "<NewInternalPort>" + NewInternalPort + "</NewInternalPort>" +
  678. "<NewInternalClient>" + InternalAddress + "</NewInternalClient>" +
  679. "<NewEnabled>1</NewEnabled>" +
  680. "<NewPortMappingDescription>" + NewPortMappingDescription + "</NewPortMappingDescription>" +
  681. "<NewLeaseDuration>" + NewLeaseDuration + "</NewLeaseDuration>" +
  682. "</u:AddPortMapping>";
  683. string result = PostSOAP(dev, srv, strData, "AddPortMapping");
  684. }
  685. private void makeDeletePortMappingSOAP(RootDevice dev, DeviceService srv, string NewRemoteHost, string NewExternalPort, string NewProtocol)
  686. {
  687. string strData = "<u:DeletePortMapping xmlns:u=\"" + srv.Type + "\">" +
  688. "<NewRemoteHost>" + NewRemoteHost + "</NewRemoteHost>" +
  689. "<NewExternalPort>" + NewExternalPort + "</NewExternalPort>" +
  690. "<NewProtocol>" + NewProtocol + "</NewProtocol>" +
  691. "</u:DeletePortMapping>";
  692. string result = PostSOAP(dev, srv, strData, "DeletePortMapping");
  693. }
  694. private string makeGetExternalIPAddress(RootDevice dev, DeviceService srv)
  695. {
  696. string strData = "<u:GetExternalIPAddress xmlns:u=\"" + srv.Type + "\">" +
  697. "</u:GetExternalIPAddress>";
  698. string result = PostSOAP(dev, srv, strData, "GetExternalIPAddress");
  699. if (result.IndexOf("<NewExternalIPAddress>") > -1)
  700. {
  701. result = result.Substring(result.IndexOf("<NewExternalIPAddress>") + 22, result.IndexOf("</NewExternalIPAddress>") - (result.IndexOf("<NewExternalIPAddress>") + 22));
  702. }
  703. else
  704. {
  705. result = "";
  706. }
  707. return result;
  708. }
  709. private string PostSOAP(RootDevice dev, DeviceService srv, string soapData, string action)
  710. {
  711. string soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
  712. "<s:Body>" + soapData + "</s:Body>" +
  713. "</s:Envelope>";
  714. string strData = "POST " + srv.BaseUrl + srv.ControlUrl + " HTTP/1.1\r\n" +
  715. "HOST: " + dev.Host + ":" + dev.Port + "\r\n" +
  716. "Content-Length: " + Encoding.UTF8.GetBytes(soap).Length.ToString() + "\r\n" +
  717. "CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n" +
  718. "SOAPACTION: \"" + srv.Type + "#" + action + "\"\r\n\r\n" + soap;
  719. byte[] data = Encoding.Default.GetBytes(strData);
  720. IPAddress ipaddr = (Dns.GetHostAddresses(dev.Host))[0];
  721. IPEndPoint IPep = new IPEndPoint(ipaddr, int.Parse(dev.Port));
  722. TcpClient tc = new TcpClient(AddressFamily.InterNetwork);
  723. NetworkStream ns = null;
  724. try
  725. {
  726. tc.Connect(IPep);
  727. ns = tc.GetStream();
  728. ns.Write(data, 0, data.Length);
  729. byte[] buffer = new byte[4096], readBuff;
  730. int ReadSize = ns.Read(buffer, 0, buffer.Length);
  731. readBuff = new byte[ReadSize];
  732. Array.Copy(buffer, 0, readBuff, 0, ReadSize);
  733. strData = Encoding.Default.GetString(readBuff);
  734. }
  735. catch { }
  736. finally
  737. {
  738. if (ns != null)
  739. {
  740. ns.Close();
  741. }
  742. tc.Close();
  743. }
  744. return strData;
  745. }
  746. public Result addPortMapping(string NewRemoteHost, string NewExternalPort, string NewProtocol, string NewInternalPort, string NewPortMappingDescription, string NewLeaseDuration)
  747. {
  748. if (this.r.Status == ResultTypes.Success)
  749. {
  750. try
  751. {
  752. this.makeAddPortMappingSOAP(this.devices[0], this.service, NewRemoteHost, NewExternalPort, NewProtocol, NewInternalPort, NewPortMappingDescription, NewLeaseDuration);
  753. }
  754. catch (Exception ex)
  755. {
  756. r.Status = ResultTypes.Faild;
  757. r.Message = ex.Message;
  758. }
  759. return this.r;
  760. }
  761. else
  762. {
  763. return this.r;
  764. }
  765. }
  766. public Result deletePortMapping(string NewRemoteHost, string NewExternalPort, string NewProtocol)
  767. {
  768. if (this.r.Status == ResultTypes.Success)
  769. {
  770. try
  771. {
  772. this.makeDeletePortMappingSOAP(this.devices[0], this.service, NewRemoteHost, NewExternalPort, NewProtocol);
  773. }
  774. catch (Exception ex)
  775. {
  776. r.Status = ResultTypes.Faild;
  777. r.Message = ex.Message;
  778. }
  779. return this.r;
  780. }
  781. else
  782. {
  783. return this.r;
  784. }
  785. }
  786. public Result getExternalIPAddress()
  787. {
  788. if (this.r.Status == ResultTypes.Success)
  789. {
  790. try
  791. {
  792. r.Message = this.makeGetExternalIPAddress(this.devices[0], this.service);
  793. }
  794. catch (Exception ex)
  795. {
  796. r.Status = ResultTypes.Faild;
  797. r.Message = ex.Message;
  798. }
  799. return this.r;
  800. }
  801. else
  802. {
  803. return this.r;
  804. }
  805. }
  806. #endregion
  807. }

这是调用方法

  1. upnpLib upnp = new upnpLib(upnpLib.InternetConnectTypes.IPv4);
  2. upnpLib.Result r = upnp.addPortMapping("200,200,200,200", "8000", "TCP", "11500", "this is uPnP Test.", "0");
  3. MessageBox.Show(r.Status == upnpLib.ResultTypes.Success ? "成功" : "失败");


这里是获取路由器uPnP命令列表

  1. upnpLib upnp = new upnpLib(upnpLib.InternetConnectTypes.IPv4);
  2. IList<upnpLib.ServicePoint> hints = upnp.ActionList;

该文章在 2021/2/2 17:42:03 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved