472,801 Members | 1,152 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,801 software developers and data experts.

UPnP code to open ports on nat/firewall

Here is some working code to open the specified TCP port on the gateway
nat device or firewall, and forward it to the calling machine. Great
for p2p apps. The newsgroups are such a great resource and have helped
me so much, I hope this helps others. Let me know if you find it

Lee Carlson
Lee (at) Carlson (dot) net

using System;
using System.Text;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;

namespace Woodchop.Net
public class UPnP
public UPnP()

public static void OpenFirewallPort(int port)
System.Net.NetworkInformation.NetworkInterface[] nics =
System.Net.NetworkInformation.NetworkInterface.Get AllNetworkInterfaces();

//for each nic in computer...
foreach (System.Net.NetworkInformation.NetworkInterface nic
in nics)
string machineIP =

//send msg to each gateway configured on this nic
(System.Net.NetworkInformation.GatewayIPAddressInf ormation gwInfo in
gwInfo.Address.ToString(), port);
{ }
catch { }

public static void OpenFirewallPort(string machineIP, string
firewallIP, int openPort)
string svc = getServicesFromDevice(firewallIP);

firewallIP, 80, openPort);
"urn:schemas-upnp-org:service:WANPPPConnection:1", machineIP,
firewallIP, 80, openPort);
private static string getServicesFromDevice(string firewallIP)
//To send a broadcast and get responses from all, send to
string queryResponse = "";
string query = "M-SEARCH * HTTP/1.1\r\n" +
"Host:" + firewallIP + ":1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"Man:\"ssdp:discover\"\r\n" +
"MX:3\r\n" +
"\r\n" +

//use sockets instead of UdpClient so we can set a
timeout easier
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint endPoint = new
IPEndPoint(IPAddress.Parse(firewallIP), 1900);

//1.5 second timeout because firewall should be on same
segment (fast)
SocketOptionName.ReceiveTimeout, 1500);

byte[] q = Encoding.ASCII.GetBytes(query);
client.SendTo(q, q.Length, SocketFlags.None, endPoint);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderEP = (EndPoint)sender;

byte[] data = new byte[1024];
int recv = client.ReceiveFrom(data, ref senderEP);
queryResponse = Encoding.ASCII.GetString(data);
catch { }

if(queryResponse.Length == 0)
return "";
/* QueryResult is somthing like this:
HTTP/1.1 200 OK
Server:NT/5.0 UPnP/1.0


string location = "";
string[] parts = queryResponse.Split(new string[] {
System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string part in parts)
if (part.ToLower().StartsWith("location"))
location = part.Substring(part.IndexOf(':') + 1);
if (location.Length == 0)
return "";

//then using the location url, we get more information:

System.Net.WebClient webClient = new WebClient();
string ret = webClient.DownloadString(location);
return ret;//return services
catch (System.Exception ex)
return "";
private static void openPortFromService(string services, string
serviceType, string machineIP, string firewallIP, int gatewayPort, int
if (services.Length == 0)
int svcIndex = services.IndexOf(serviceType);
if (svcIndex == -1)
string controlUrl = services.Substring(svcIndex);
string tag1 = "<controlURL>";
string tag2 = "</controlURL>";
controlUrl = controlUrl.Substring(controlUrl.IndexOf(tag1)
+ tag1.Length);
controlUrl =
string soapBody = "<s:Envelope " +
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/ \" " +

"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/ \">" +
"<s:Body>" +
"<u:AddPortMapping xmlns:u=\"" + serviceType + "\">" +
"<NewRemoteHost></NewRemoteHost>" +
"<NewExternalPort>" + portToForward.ToString() +
"</NewExternalPort>" +
"<NewProtocol>TCP</NewProtocol>" +
"<NewInternalPort>" + portToForward.ToString() +
"</NewInternalPort>" +
"<NewInternalClient>" + machineIP +
"</NewInternalClient>" +
"<NewEnabled>1</NewEnabled>" +
Client</NewPortMappingDescription>" +
"<NewLeaseDuration>0</NewLeaseDuration>" +
"</u:AddPortMapping>" +
"</s:Body>" +

byte[] body =

string url = "http://" + firewallIP + ":" +
gatewayPort.ToString() + controlUrl;
System.Net.WebRequest wr =
System.Net.WebRequest.Create(url);//+ controlUrl);
wr.Method = "POST";
wr.Headers.Add("SOAPAction","\"" + serviceType +
wr.ContentType = "text/xml;charset=\"utf-8\"";
wr.ContentLength = body.Length;

System.IO.Stream stream = wr.GetRequestStream();
stream.Write(body, 0, body.Length);

WebResponse wres = wr.GetResponse();
System.IO.StreamReader sr = new
string ret = sr.ReadToEnd();

Debug.WriteLine("Setting port forwarding:" +
portToForward.ToString() + "\r\r" + ret);

Dec 3 '05 #1
0 26758

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Cliff | last post by:
I need to get a list of "Open"/In-Use TCP Ports (actually to see if there is a cponnection with a destination Port of 21) I think what I'm after is similar to the output of netstat. I could run...
by: bsimaie | last post by:
Hello, could somebody help me to convert the below UPnP service filr to WSDL web servive file: <serviceList> <service> <serviceType> urn:schemas-upnp-org:service:PowerSwitch:1 </serviceType>...
by: Robert S | last post by:
Hello, could somebody help me to convert the below UPnP service file to WSDL web service file: <serviceList> <service> <serviceType> urn:schemas-upnp-org:service:PowerSwitch:1 </serviceType>...
by: Robert S | last post by:
Hello group, I tried to combine UPnP servive and blenderpowerSCPD.xml and come up with WSDL web service file as below: UPnP services: <serviceList>
by: Manohar Kamath | last post by:
Hello all, Consider that you have an ASP.NET application you have deployed as www.somesite.com. If I would like to create an intranet site with the same code (say http://intranetsite/ for use...
by: Noone Here | last post by:
AIUI, it was not all that long ago when the threat to personal users, was attachments that when executed compromised machines with keyloggers, trojans, etc. Now it seems that the big problem is...
by: xlar54 | last post by:
Ive searched around and Im hazy on what is needed to develop media server code. Is there a UPnP library for C#? Linux apparently has many, and I even found a Java one, but can't locate anything...
by: Laszlo Nagy | last post by:
Hi All, I'm using a simple program that uploads a file on a remote ftp server. This is an example (not the whole program): def store(self,hostname,username,password,destdir,srcpath):...
by: Svinja | last post by:
Hello, I am using UPnP in c# to communicate with my router. So far i have managed to do this: 1. Get router info(xml) 2. Get external(public) IP address 3. Add and delete port mapping Is...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: lllomh | last post by:
How does React native implement an English player?
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.