Author: Tomas Rutkauskas
Detect an HTTP proxy
Answer:
If you write a core http client, e.g. from socket level, you may need to detect
whether there is an http proxy used. This includes the name of the proxy server and
the port number it operates on. Such proxy servers are often used where a firewall
is installed.
Luckily IE is installed on many Windows systems, and IE puts this information in
the registry under
\Software\Microsoft\Windows\CurrentVersion\Internet Settings
The following procedure GetProxy retrieves the host name, port number and whether
the proxy is enabled. You can use it as shown in the FormCreate() event handler.
Note: The value ProxyEnable should be a DWord, but sometimes it may be stored as
binary or as a string, depending on the version of IE that the user has installed.
The code below evaluates the type and reads it appropriately.
1 unit fProxy;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 Registry;
8
9 type
10 TForm1 = class(TForm)
11 procedure FormCreate(Sender: TObject);
12 private
13 { private declarations }
14 public
15 { public declarations }
16 end;
17
18 var
19 Form1: TForm1;
20
21 implementation
22
23 {$R *.DFM}
24
25 function GetProxy(var Host: string; var Port: integer; var ProxyEnabled: boolean):
26 boolean;
27 var
28 s: string;
29 p: integer;
30 begin
31 with TRegistry.Create do
32 begin
33 RootKey := HKEY_CURRENT_USER;
34 ProxyEnabled := false;
35 s := '';
36 OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', True);
37 if ValueExists('ProxyServer') then
38 s := ReadString('ProxyServer');
39
40 if s <> '' then
41 begin
42 p := pos(':', s);
43 if p = 0 then
44 p := length(s) + 1;
45 Host := copy(s, 1, p - 1);
46 try
47 Port := StrToInt(copy(s, p + 1, 999));
48 except
49 Port := 80;
50 end;
51
52 ProxyEnabled := true;
53 end;
54
55 if ValueExists('ProxyEnable') then
56 begin
57 case GetDataType(sProxyEnable) of
58 rdString,
59 rdExpandString:
60 begin
61 sPortTmp := AnsiLowerCase(ReadString(sProxyEnable));
62 ProxyEnabled := true;
63 if pos(' ' + sPortTmp + ' ', ' yes true t enabled 1 ') > 0 then
64 ProxyEnabled := true
65 else if pos(' ' + sPortTmp + ' ', ' no false f none disabled 0 ') > 0
66 then
67 ProxyEnabled := false
68 end;
69 rdInteger:
70 begin
71 ProxyEnabled := ReadBool(sProxyEnable);
72 end;
73 rdBinary:
74 begin
75 ProxyEnabled := true;
76 ReadBinaryData(sProxyEnable, ProxyEnabled, 1);
77 end;
78 end;
79 end;
80
81 Free;
82 end;
83
84 Result := s <> '';
85 end;
86
87 procedure TForm1.FormCreate(Sender: TObject);
88 var
89 Host: string;
90 Port: integer;
91 ProxyEnabled: boolean;
92 const
93 YesNo: array[false..true] of string = (' not ', '');
94 begin
95 // get proxy information
96 if GetProxy(Host, Port, ProxyEnabled) then
97 ShowMessage(Format('Your proxy is %s on port %d, it is%s enabled.', [Host,
98 Port, YesNo[ProxyEnabled]]))
99 else
100 ShowMessage('No proxy detected');
101 end;
102
103 end.
|