Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "403 Forbidden" when I connect to whatismyip.com?

Tags:

delphi

With the following code, I get exception class EIdHTTPProtocolException with message 'HTTP/1.1 403 Forbidden'. Process svchostip.exe (11172)

function GetInternetIP:string;
var
  IdHTTPMainUrl : TIdHTTP;
begin
  try
    IdHTTPMainUrl := TIdHTTP.Create(nil);
    IdHTTPMainUrl.Request.Host := 'http://www.whatismyip.com/automation/n09230945.asp';
    Result := idHTTPMainUrl.Get('http://automation.whatismyip.com/n09230945.asp');
  except
    IdHTTPMainUrl.Free;
  end;
end;
like image 291
Sergei Shardiko Avatar asked Jun 03 '12 13:06

Sergei Shardiko


1 Answers

You need to set your user agent, this is documented in WhatIsMyIP faq:

•Please set your program's user agent to Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 , this will keep your program from being blocked by CloudFlare

Also freeing the TIdHTTP instance should be unconditional, you're only freeing it when an exception is thrown. Use exception handling, well, to handle exceptions.

function GetInternetIP:string;
var
  IdHTTPMainUrl : TIdHTTP;
begin
  IdHTTPMainUrl := TIdHTTP.Create(nil);
  try
    IdHTTPMainUrl.Request.UserAgent :=
      'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0';
    Result := idHTTPMainUrl.Get('http://automation.whatismyip.com/n09230945.asp');
  finally
    IdHTTPMainUrl.Free;
  end;
end;
like image 199
Sertac Akyuz Avatar answered Oct 29 '22 05:10

Sertac Akyuz