Thursday, September 5, 2013

UPnP Code for Windows XP, 7 and possibly 8 - Part 1

Well getting to this one and making a component was really tough and after too much frustration that I got to know about the dependency of provided WinAPI methods on the version of the windows. I am putting the simplified version here so no other gets to be the one stuck...

Oh I also found out that there is a code independent of platform embedded in libjingle somewhere, will investigate in the coming days.

Rambling; Why Blogspot, why? Why don't you have tab functionality here and an option for indenting would have done wonders to the readability of my codes...



WinXP


uses
  Windows, Variants, Winsock, SysUtils, ComObj;

...

const 

  // for the AProtocol Argument

  TCP_PORT = 6; 
  UDP_PORT = 17; 

...

procedure Upnp_AddPort ( AName : String; APort : WORD; AProtocol : Byte );
var
  Nat, Profile, Ports : Variant; 

begin

  Nat := CreateOleObject ( 'HNetCfg.FwMgr' );
  Profile := Nat.LocalPolicy.CurrentProfile;

  if VarIsClear ( Profile ) then exit;

  Ports := CreateOLEObject('HNetCfg.FWOpenPort');
  Ports.Name := AName;
  Ports.Protocol := AProtocol;
  Ports.Port := APort;
  Ports.Scope := 0;
  Ports.Enabled := True;

  Profile.GloballyOpenPorts.Add ( Ports );

end;

procedure Upnp_RemovePort ( APort : WORD; AProtocol : Byte );
var
  Nat, Profile : Variant;

begin

  Nat := CreateOleObject ( 'HNetCfg.FwMgr' );
  Profile := Nat.LocalPolicy.CurrentProfile;
  Profile.GlobalyOpenPorts.Remove ( APort, AProtocol );

end;

No comments:

Post a Comment