473,788 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
useful!

Lee Carlson
Lee (at) Carlson (dot) net
-----------------------------------

using System;
using System.Text;
using System.Diagnost ics;
using System.Net.Sock ets;
using System.Net;

namespace Woodchop.Net
{
public class UPnP
{
public UPnP()
{

}
public static void OpenFirewallPor t(int port)
{
System.Net.Netw orkInformation. NetworkInterfac e[] nics =
System.Net.Netw orkInformation. NetworkInterfac e.GetAllNetwork Interfaces();

//for each nic in computer...
foreach (System.Net.Net workInformation .NetworkInterfa ce nic
in nics)
{
try
{
string machineIP =
nic.GetIPProper ties().UnicastA ddresses[0].Address.ToStri ng();

//send msg to each gateway configured on this nic
foreach
(System.Net.Net workInformation .GatewayIPAddre ssInformation gwInfo in
nic.GetIPProper ties().GatewayA ddresses)
{
try
{
OpenFirewallPor t(machineIP,
gwInfo.Address. ToString(), port);
}
catch
{ }
}
}
catch { }
}

}
public static void OpenFirewallPor t(string machineIP, string
firewallIP, int openPort)
{
string svc = getServicesFrom Device(firewall IP);

openPortFromSer vice(svc,"urn:s chemas-upnp-org:service:WAN IPConnection:1" ,machineIP,
firewallIP, 80, openPort);
openPortFromSer vice(svc,
"urn:schema s-upnp-org:service:WAN PPPConnection:1 ", machineIP,
firewallIP, 80, openPort);
}
private static string getServicesFrom Device(string firewallIP)
{
//To send a broadcast and get responses from all, send to
239.255.255.250
string queryResponse = "";
try
{
string query = "M-SEARCH * HTTP/1.1\r\n" +
"Host:" + firewallIP + ":1900\r\n" +
"ST:upnp:rootde vice\r\n" +
"Man:\"ssdp:dis cover\"\r\n" +
"MX:3\r\n" +
"\r\n" +
"\r\n";

//use sockets instead of UdpClient so we can set a
timeout easier
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
IPEndPoint endPoint = new
IPEndPoint(IPAd dress.Parse(fir ewallIP), 1900);

//1.5 second timeout because firewall should be on same
segment (fast)
client.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t, 1500);

byte[] q = Encoding.ASCII. GetBytes(query) ;
client.SendTo(q , q.Length, SocketFlags.Non e, endPoint);
IPEndPoint sender = new IPEndPoint(IPAd dress.Any, 0);
EndPoint senderEP = (EndPoint)sende r;

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

if(queryRespons e.Length == 0)
return "";
/* QueryResult is somthing like this:
*
HTTP/1.1 200 OK
Cache-Control:max-age=60
Location:http://10.10.10.1:80/upnp/service/des_ppp.xml
Server:NT/5.0 UPnP/1.0
ST:upnp:rootdev ice
EXT:

USN:uuid:upnp-InternetGateway Device-1_0-00095bd945a2::u pnp:rootdevice
*/

string location = "";
string[] parts = queryResponse.S plit(new string[] {
System.Environm ent.NewLine }, StringSplitOpti ons.RemoveEmpty Entries);
foreach (string part in parts)
{
if (part.ToLower() .StartsWith("lo cation"))
{
location = part.Substring( part.IndexOf(': ') + 1);
break;
}
}
if (location.Lengt h == 0)
return "";

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

System.Net.WebC lient webClient = new WebClient();
try
{
string ret = webClient.Downl oadString(locat ion);
Debug.WriteLine (ret);
return ret;//return services
}
catch (System.Excepti on ex)
{
Debug.WriteLine (ex.Message);
}
finally
{
webClient.Dispo se();
}
return "";
}
private static void openPortFromSer vice(string services, string
serviceType, string machineIP, string firewallIP, int gatewayPort, int
portToForward)
{
if (services.Lengt h == 0)
return;
int svcIndex = services.IndexO f(serviceType);
if (svcIndex == -1)
return;
string controlUrl = services.Substr ing(svcIndex);
string tag1 = "<controlUR L>";
string tag2 = "</controlURL>";
controlUrl = controlUrl.Subs tring(controlUr l.IndexOf(tag1)
+ tag1.Length);
controlUrl =
controlUrl.Subs tring(0,control Url.IndexOf(tag 2));
string soapBody = "<s:Envelop e " +
"xmlns:s=\"http ://schemas.xmlsoap .org/soap/envelope/ \" " +

"s:encodingStyl e=\"http://schemas.xmlsoap .org/soap/encoding/ \">" +
"<s:Body>" +
"<u:AddPortMapp ing xmlns:u=\"" + serviceType + "\">" +
"<NewRemoteHost ></NewRemoteHost>" +
"<NewExternalPo rt>" + portToForward.T oString() +
"</NewExternalPort >" +
"<NewProtocol>T CP</NewProtocol>" +
"<NewInternalPo rt>" + portToForward.T oString() +
"</NewInternalPort >" +
"<NewInternalCl ient>" + machineIP +
"</NewInternalClie nt>" +
"<NewEnable d>1</NewEnabled>" +
"<NewPortMappin gDescription>Wo odchop
Client</NewPortMappingD escription>" +
"<NewLeaseDurat ion>0</NewLeaseDuratio n>" +
"</u:AddPortMappin g>" +
"</s:Body>" +
"</s:Envelope>";

byte[] body =
System.Text.UTF 8Encoding.ASCII .GetBytes(soapB ody);

string url = "http://" + firewallIP + ":" +
gatewayPort.ToS tring() + controlUrl;
System.Net.WebR equest wr =
System.Net.WebR equest.Create(u rl);//+ controlUrl);
wr.Method = "POST";
wr.Headers.Add( "SOAPAction","\ "" + serviceType +
"#AddPortMappin g\"");
wr.ContentType = "text/xml;charset=\"u tf-8\"";
wr.ContentLengt h = body.Length;

System.IO.Strea m stream = wr.GetRequestSt ream();
stream.Write(bo dy, 0, body.Length);
stream.Flush();
stream.Close();

WebResponse wres = wr.GetResponse( );
System.IO.Strea mReader sr = new
System.IO.Strea mReader(wres.Ge tResponseStream ());
string ret = sr.ReadToEnd();
sr.Close();

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

Dec 3 '05 #1
0 27052

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

Similar topics

0
469
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 netstat and parse the output, but I'd prefer not to as I'm going to be doing this in a service and it needs to monitor the ports every few seconds. Any advice on how I can do it.
0
1718
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> <serviceId> urn:upnp-org:service:PowerSwitch:1 </serviceId>
1
3567
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> <serviceId> urn:upnp-org:service:PowerSwitch:1
0
1731
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>
3
1554
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 within the company firewall) , I could just point another IIS web site to the same code location, without having to re-deploy. I have tried this, and it works fine. However, I would like to know if anyone has run into issues in this scenario....
28
3035
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 reading a webpage or an HTML e-mail and getting affected through the scripting. My understanding is that the script downloads the malicious program from the web and sets it to run on start up through the start-up folder or in the registry. I...
1
20452
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 yet for dotNET.
1
4133
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): self.ftp = ftplib.FTP(hostname) self.ftp.login(username,password) self.ftp.set_pasv(False)
2
2982
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 there any way to see which ports are forwarded? I think it is possible with eventing but my router doesnt support it. I tried with queryStateVariable action but with no success. I am not using NAT traversal.
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.