通过使用"HNetCfg.NATUPnP"进行端口转发. Ole对象失败 [英] Port Forwarding by Using "HNetCfg.NATUPnP" Ole Object Failed
问题描述
我正在使用代码转发端口.该代码在My Windows 7上正常运行;但是我不能在Windows XP上使用它.
I am using a code for forwarding a port. this code works fine on My Windows 7; but I can't use It on Windows XP.
更新1个问题(2012-10-17 07:32:00Z)
这是我的源代码:
uses
ActiveX, oleAuto;
Procedure AddUPnPEntry(Port: Integer; const Name: ShortString; LAN_IP: string);
Var
Nat: Variant;
Ports: Variant;
SavedCW: Word;
Begin
if NOT(LAN_IP = '127.0.0.1') then
begin
try
Nat := CreateOleObject('HNetCfg.NATUPnP');
Ports := Nat.StaticPortMappingCollection;
// Error Raized From Here!!!
ShowMessage(inttostr(Ports.count));
Ports.Add(Port, 'TCP', Port, LAN_IP, True, name);
except
ShowMessage('An Error occured with adding UPnP Ports. The ' + name +
' port was not added to the router. Please check to see if your ' +
'router supports UPnP and has it enabled or disable UPnP.');
end;
end;
End;
procedure TForm1.Button2Click(Sender: TObject);
begin
AddUPnPEntry(1234, 'Hello3', '192.168.1.1');
end;
AV错误消息:
Project Project1.exe raised exception class $C0000005 with message 'access violation at 0x00504876: read of address 0x00000000'.
推荐答案
如果遇到访问冲突,则在访问count属性时,这意味着 IUPnPNAT.get_StaticPortMappingCollection
方法是nil
,这可能是由于出于多种原因,您的设备不支持UPnP,未在设备上启用UPnP,未安装/激活UPnP用户界面,依此类推.
If you are getting an access violation, when you access the count property, this means which the IStaticPortMappingCollection
interface returned by the IUPnPNAT.get_StaticPortMappingCollection
method is nil
, this can be caused by many reasons your device doesn't supports UPnP, The UPnP is not enabled on the device, The UPnP User Interface is not installed/active, and so on.
无论如何要防止这种异常(访问冲突),您必须在使用属性或方法之前检查它所返回的值,在这种情况下,您可以使用
Anyway to prevent this kind of exceptions (the access violation) you must check the value returned by the property or method before to use it, in this case you can use the VarIsClear
function like so :
try
Nat := CreateOleObject('HNetCfg.NATUPnP');
Ports := Nat.StaticPortMappingCollection;
if not VarIsClear(Ports) then
begin
//do something
ShowMessage(inttostr(Ports.count));
Ports.Add(Port, 'TCP', Port, LAN_IP, True, name);
end;
except on E:Exception do
ShowMessage('An Error occured with adding UPnP Ports. '+E.Message);
end;
这篇关于通过使用"HNetCfg.NATUPnP"进行端口转发. Ole对象失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!