Simple Port Mapping Example

Coordinator
May 27, 2011 at 12:44 PM
Edited May 31, 2011 at 2:27 AM
Here is a simple example using synchronous discovery (for simplicity's sake) to add and delete a port mapping for a Gateway Device:
using ManagedUPnP;
...
 // Finding service...
 Service lsService = null;
 
 Services lsServices = Discovery.FindServices("urn:schemas-upnp-org:service:WANPPPConnection:1");
 
 if (lsServices.Count > 0)
     lsService = lsServices[0];
 else
 {
     // No Valid Service Found
     return;
 }
 
 try
 {
     // Add the port mapping
     object[] loObj = new object[] { "", 29679, "UDP", 29679, "192.168.0.24", true, "Custom Mapping", 0 };
     lsService.InvokeAction("AddPortMapping", loObj);

     // Remove the port mapping
     loObj = new object[] { "", 29679, "UDP" };
     lsService.InvokeAction("DeletePortMapping", loObj);
 }
 catch (Exception loE)
 {
     MessageBox.Show(
         String.Format(
             "{0}: HTTPSTATUS: {1}",
             loE.Message,
             lsService.LastTransportStatus));
 }