virusssss 0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
||||
1 |
||||
18.01.2015, 23:50. Показов 11875. Ответов 20 Метки нет (Все метки)
Всем привет!
__________________
0 |
Dryg 71 / 66 / 35 Регистрация: 09.04.2009 Сообщений: 364 Записей в блоге: 1 |
||||
19.01.2015, 09:28 |
2 |
|||
idhttp1.host:=(‘google.ru’); надо указывать http или https, а то он не понимает, что ты хочешь от него
0 |
Модератор 3487 / 2610 / 741 Регистрация: 19.09.2012 Сообщений: 7,971 |
|
19.01.2015, 09:48 |
3 |
И условие перепутано.
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
19.01.2015, 10:45 |
4 |
надо указывать http или https, а то он не понимает Ерунда полная.
0 |
71 / 66 / 35 Регистрация: 09.04.2009 Сообщений: 364 Записей в блоге: 1 |
|
19.01.2015, 10:57 |
5 |
Ерунда полная поясни!
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
19.01.2015, 11:05 |
6 |
св-во Host требуется для указания имени хоста https://www.google.ru/ — это не имя хоста, а URL Имя хоста в составе URL — это www.google.ru, все остальное в URL не имеет к имени (адресу) хоста ни малейшего отношения
0 |
71 / 66 / 35 Регистрация: 09.04.2009 Сообщений: 364 Записей в блоге: 1 |
|
19.01.2015, 11:32 |
7 |
св-во Host требуется для указания имени хоста Не хочу свое Фи говорить, но ты не прав На сколько я знаю без протокола вообще не работает Миниатюры
0 |
Dryg 71 / 66 / 35 Регистрация: 09.04.2009 Сообщений: 364 Записей в блоге: 1 |
||||
19.01.2015, 11:35 |
8 |
|||
и дате www не обязательно указывать
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
19.01.2015, 12:25 |
9 |
без протокола вообще не работает Разбор целевого URL (в т.ч. протокола, явно указанного порта и пр.) осуществляют методы GET, PUT, HEAD На момент выполнения Connect URL уже должен быть разобран. Рез-ты разбора помещаются с учетом настроек прокси и IOHandler’а помещаются в защищенное св-во Host. Добавлено через 2 минуты только лишь для проверки доступности хоста по протоколу TCP совершенно неразумно — на то есть TIdTCPConnection
0 |
0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
|
19.01.2015, 13:40 [ТС] |
10 |
подскажите пожалуйста, как изменить код чтобы можно было проверять доступность адреса сайта указанного, но не выдавало ошибку в случаи false.
0 |
71 / 66 / 35 Регистрация: 09.04.2009 Сообщений: 364 Записей в блоге: 1 |
|
19.01.2015, 14:11 |
11 |
ошибка Шмыг! какая версия у тебя Delphi и indy?
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
19.01.2015, 14:27 |
12 |
Если хоста нет Так тебе не хост нужно проверять, а именно доступность интересующего тебя ресурса на данном хосте) Сделай Head-запрос, заключив его в блок try..except — это минимально необходимые и достаточные действия.
0 |
0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
|
19.01.2015, 18:56 [ТС] |
13 |
delphi 7, indy все стандартное.
0 |
mss 2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
||||
19.01.2015, 22:57 |
14 |
|||
Не по теме:
куда совать Я бы сказал куда, но не в прямом эфире)
0 |
virusssss 0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
||||
19.01.2015, 23:22 [ТС] |
15 |
|||
при подставки хоть валидного хоть НЕвалидного сайта, все равно срабатывает error.html. Добавлено через 6 минут Добавлено через 13 минут
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
20.01.2015, 08:12 |
16 |
все равно срабатывает error.html К валидности или НЕвалидности хоста (и сайта) это не имеет отношения.
все равно выдает ошибку socket error # 11001 host not found Брейкпойнт в теле exept-блока при этом ловится ?
0 |
0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
|
20.01.2015, 13:52 [ТС] |
17 |
Брейкпойнт в теле exept-блока при этом ловится ? не понял о чем речь.
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
20.01.2015, 14:22 |
18 |
об использовании встроенного в IDE отладчика
0 |
virusssss 0 / 0 / 0 Регистрация: 14.01.2015 Сообщений: 20 |
||||
20.01.2015, 14:54 [ТС] |
19 |
|||
об использовании встроенного в IDE отладчика видите ли, не совсем в теме, не волшебник еще. Эта сторона делфи мне далека. Добавлено через 8 минут
0 |
2649 / 2270 / 279 Регистрация: 24.12.2010 Сообщений: 13,725 |
|
20.01.2015, 16:09 |
20 |
Эта сторона делфи мне далека Но именно с этой стороны следует заходить в Делфи)
0 |
Socket error 11001 delphi
Что можно сделать чтобы избавится от «выскакивания» окна с сообщением об ошибке 11001 и других ошибок, которые не устраняются с помощью:
procedure TForm1.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
.
ErrorCode:=0;
.
end;
И вообще как эти ошибки можно обработать програмно?
← →
Анатолий ( 2003-09-28 20:32 ) [1]
если знаешь часть кода на которой бывает ошибка попробуй заключить ее в try . except
← →
SergP ( 2003-09-28 20:54 ) [2]
Ошибка 11001 возникает при попытке конекта клиентсокета когда у меня инет отключен. Но что заключать в try..except..end;?
Clientsocket.open пробовал заключать — не помогает.
← →
Sergp ( 2003-09-29 14:01 ) [3]
Ну что? Никто не подскажет?
Дело в том что как-то некрасиво когда в проге выскакивают сообщения об ошибках, пусть даже и в тот момент когда ее нельзя использовать.
← →
Анатолий ( 2003-09-29 14:04 ) [4]
найди отладчиком момент возникновения ошибки, может это не cs.open а где то в другом месте ? пройди по проге пошагам и найди.
Application.OnException поймает все не обработанные исключения
← →
Sergp ( 2003-09-29 14:24 ) [6]
> Анатолий (29.09.03 14:04) [4]
> найди отладчиком момент возникновения ошибки, может это
> не cs.open а где то в другом месте ? пройди по проге пошагам
> и найди.
В хелпе написано :
11001 Authoritative answer: Host not found.
У меня так оно и есть. Неподключен к инету — возникают такие ошибки при попытке сокета сконектиться. Так что имхо однозначно в этом виноват clientsocket при попытке сделать ему open.
насчет отладчика попытаюсь.
> Polevi © (29.09.03 14:05) [5]
> Application.OnException поймает все не обработанные исключения
Можно подробнее с небольшим примерчиком?
Да и кстати, у меня иногда (очень редко при работе проги вылезает окно с ошибкой вроде External exception 80000003 (точно не помню) , что это такое? И можно ли с помощью Application.OnException и ее тоже устранить?
← →
Sergp ( 2003-09-29 14:24 ) [7]
> Анатолий (29.09.03 14:04) [4]
> найди отладчиком момент возникновения ошибки, может это
> не cs.open а где то в другом месте ? пройди по проге пошагам
> и найди.
В хелпе написано :
11001 Authoritative answer: Host not found.
У меня так оно и есть. Неподключен к инету — возникают такие ошибки при попытке сокета сконектиться. Так что имхо однозначно в этом виноват clientsocket при попытке сделать ему open.
насчет отладчика попытаюсь.
> Polevi © (29.09.03 14:05) [5]
> Application.OnException поймает все не обработанные исключения
Можно подробнее с небольшим примерчиком?
Да и кстати, у меня иногда (очень редко при работе проги вылезает окно с ошибкой вроде External exception 80000003 (точно не помню) , что это такое? И можно ли с помощью Application.OnException и ее тоже устранить?
← →
Polevi ( 2003-09-29 14:51 ) [8]
окно можно устранить, но ты лучше устрани причину
← →
nikkie ( 2003-09-29 16:18 ) [9]
а почему ты думаешь, что ошибку вызывает серверный сокет? скорее клиентский — и обрабатывать ошибку надо в СlientSocket.OnError.
Хм. Опять как оказалось не тот кусок кода написал. Просто обработчики у меня почти одинаковые.
Вот точная копия обоих обработчиков. В обоих я Errorcode устанавливаю в 0, но это не помогает. И по всей видимости при ошибке 11001 OnError не вызывается.
procedure TForm1.ClientSocketError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
memo1.lines.add(«CSError «+inttostr(ErrorCode)+» «+inttostr(integer(sender)));
TCustomWinSocket(socket.data).free;
ErrorCode:=0;
PostMessage(Form1.Handle, KILL_SOCKET, 0,integer(Sender));
end;
procedure TForm1.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
memo1.lines.add(«SSError «+inttostr(ErrorCode)+» «+inttostr(integer(socket.data)));
KSocket(socket.data).free;
ErrorCode:=0;
Postmessage(Form1.Handle, KILL_SOCKET, integer(socket),0);
end;
А насчет второй ошибки, я даже не могу понять от чего она возникает, причем очень редко. Вроде бы уже принял все меры против этого.
← →
aprm_85 ( 2003-09-30 22:52 ) [11]
А может прежде чем коннектится к хосту, проверить, есть ли Инет?
Если dial-up, все просто: TMagRAs (компонент для работы с dialup)
С выделенкой — сложнее. там возможгы варианты
← →
SergP ( 2003-10-01 07:21 ) [12]
> aprm_85 © (30.09.03 22:52) [11]
> А может прежде чем коннектится к хосту, проверить, есть
> ли Инет?
> Если dial-up, все просто: TMagRAs (компонент для работы
> с dialup)
> С выделенкой — сложнее. там возможгы варианты
Это ИМХО излишне. Да и как оказалось эта ошибка ловится Application.OnException как советовал Polevi. Просто я этой штукой никогда не пользовался раньше и сначала не пользовался потому, что хотел бы иметь сначала пример прежде чем использовать, но в связи с тем что примера так и никто не дал, пришлось самому экспериментировать.
← →
nikkie ( 2003-10-01 13:44 ) [13]
Application.OnException — это, конечно, лом, против которого нет приема. Только прибегать к нему стоит, если ты совсем сдался сделать по нормальному.
Я только что попробовал — 11001, «Windows socket error: No such host is known (11001), on API «ASync Lookup»» прекрасно ловится и гасится в OnError (по-крайней мере в D6). Ты пробовал это в тестовом приложении — один клиентский сокет на форме? Попробуй. И покажи, как ты создаешь сокет в приложении, где у тебя проблема.
← →
SergP ( 2003-10-02 08:56 ) [14]
2 nikkie У меня D5. Да и переходить на D6 почему-то не очень хочется. Хотя возможно что придется. Не знаю почему оно у Вас ловится в onError, но у меня ловятся там все остальные ошибки кроме 11001.
А насчет того чтобы показать как что и где я создаю — может лучше я скину исходник на мыло? А то много постить тут нужно.
по кр.мере в D5 отказ с кодом WSAHOST_NOT_FOUND = 11001 не может быт перехвачен в событии OnError, только — в App.OnException
этому есть вполне четкое объяснение, достаточно взглянуть в исх.текст компонента
procedure TCustomWinSocket.CMLookupComplete(var Message: TCMLookupComplete);
begin
if Message.LookupHandle = FLookupHandle then
begin
FLookupHandle := 0;
if Message.AsyncError <> 0 then
begin
Disconnect(FSocket);
raise ESocketError.CreateResFmt(@sWindowsSocketError,
[SysErrorMessage(Message.AsyncError), Message.ASyncError, «ASync Lookup»]);
end;
.
end;
end;
← →
Digitman ( 2003-10-02 09:29 ) [16]
для того чтобы избавиться от вынужденной обработки отказа в App.OnException, необходимо явно св-ва Address и Port (т.е. явный IP-адрес и явный номер порта), оставляя св-ва Host и Service пустыми
в этом случае не будут задействованы службы, разрешающие имя хоста в его адрес и имя сервиса в номер соотв.порта
как раз эти службы, будучи задействованными при неуказании явно адреса и порта, вызывают внутри компонента ф-ции [WSAAsync]GetHostByName (хост -> адрес) и [WSAASync]GetServByName (имя сервиса -> номер порта) . именно эти ф-ции генерируют отказ с упомянутым кодом, и отказ этот обрабатывается компонентом столь нецдобно, по твоему мнению.
есть другие варианты — работать либо с блок.гнездом (тогда исключения во всех методах компонента «ловятся» банальным try..except) либо работать с неблок.гнездом, но указывать адрес+порт явно, проводя перед коннектом разрешение имен самостоятельно явными вызовами вышеупомянутых Winsock-ф-ций.
← →
nikkie ( 2003-10-02 13:46 ) [17]
что ж, значит, в D5 действительно нужен лом. а в D6 код такой:
procedure TCustomWinSocket.CMLookupComplete(var Message: TCMLookupComplete);
var
ErrorCode: Integer;
begin
if Message.LookupHandle = FLookupHandle then
begin
FLookupHandle := 0;
if Message.AsyncError <> 0 then
begin
ErrorCode := Message.AsyncError;
Error(Self, eeLookup, ErrorCode);
Disconnect(FSocket);
if ErrorCode <> 0 then
raise ESocketError.CreateResFmt(@sWindowsSocketError,
[SysErrorMessage(Message.AsyncError), Message.ASyncError, «ASync Lookup»]);
Exit;
end;
.
end;
end;
← →
Digitman ( 2003-10-02 14:09 ) [18]
скорее всего это был маленький недосмотр со стороны Борланда
Источник
← →
SergP
(2003-09-28 13:23)
[0]
Что можно сделать чтобы избавится от «выскакивания» окна с сообщением об ошибке 11001 и других ошибок, которые не устраняются с помощью:
procedure TForm1.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
…
ErrorCode:=0;
…
end;
И вообще как эти ошибки можно обработать програмно?
← →
Анатолий
(2003-09-28 20:32)
[1]
если знаешь часть кода на которой бывает ошибка попробуй заключить ее в try … except
← →
SergP
(2003-09-28 20:54)
[2]
Ошибка 11001 возникает при попытке конекта клиентсокета когда у меня инет отключен. Но что заключать в try..except..end;?
Clientsocket.open пробовал заключать — не помогает.
← →
Sergp
(2003-09-29 14:01)
[3]
Ну что? Никто не подскажет?
Дело в том что как-то некрасиво когда в проге выскакивают сообщения об ошибках, пусть даже и в тот момент когда ее нельзя использовать…
← →
Анатолий
(2003-09-29 14:04)
[4]
найди отладчиком момент возникновения ошибки, может это не cs.open а где то в другом месте ? пройди по проге пошагам и найди…
← →
Polevi
(2003-09-29 14:05)
[5]
Application.OnException поймает все не обработанные исключения
← →
Sergp
(2003-09-29 14:24)
[6]
> Анатолий (29.09.03 14:04) [4]
> найди отладчиком момент возникновения ошибки, может это
> не cs.open а где то в другом месте ? пройди по проге пошагам
> и найди…
В хелпе написано :
11001 Authoritative answer: Host not found.
У меня так оно и есть… Неподключен к инету — возникают такие ошибки при попытке сокета сконектиться. Так что имхо однозначно в этом виноват clientsocket при попытке сделать ему open…
насчет отладчика попытаюсь…
> Polevi © (29.09.03 14:05) [5]
> Application.OnException поймает все не обработанные исключения
Можно подробнее с небольшим примерчиком?
Да и кстати, у меня иногда (очень редко при работе проги вылезает окно с ошибкой вроде External exception 80000003 (точно не помню) , что это такое? И можно ли с помощью Application.OnException и ее тоже устранить?
← →
Sergp
(2003-09-29 14:24)
[7]
> Анатолий (29.09.03 14:04) [4]
> найди отладчиком момент возникновения ошибки, может это
> не cs.open а где то в другом месте ? пройди по проге пошагам
> и найди…
В хелпе написано :
11001 Authoritative answer: Host not found.
У меня так оно и есть… Неподключен к инету — возникают такие ошибки при попытке сокета сконектиться. Так что имхо однозначно в этом виноват clientsocket при попытке сделать ему open…
насчет отладчика попытаюсь…
> Polevi © (29.09.03 14:05) [5]
> Application.OnException поймает все не обработанные исключения
Можно подробнее с небольшим примерчиком?
Да и кстати, у меня иногда (очень редко при работе проги вылезает окно с ошибкой вроде External exception 80000003 (точно не помню) , что это такое? И можно ли с помощью Application.OnException и ее тоже устранить?
← →
Polevi
(2003-09-29 14:51)
[8]
окно можно устранить, но ты лучше устрани причину
← →
nikkie
(2003-09-29 16:18)
[9]
а почему ты думаешь, что ошибку вызывает серверный сокет? скорее клиентский — и обрабатывать ошибку надо в СlientSocket.OnError.
← →
Sergp
(2003-09-29 19:38)
[10]
Хм… Опять как оказалось не тот кусок кода написал. Просто обработчики у меня почти одинаковые…
Вот точная копия обоих обработчиков. В обоих я Errorcode устанавливаю в 0, но это не помогает. И по всей видимости при ошибке 11001 OnError не вызывается…
procedure TForm1.ClientSocketError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
memo1.lines.add(«CSError «+inttostr(ErrorCode)+» «+inttostr(integer(sender)));
TCustomWinSocket(socket.data).free;
ErrorCode:=0;
PostMessage(Form1.Handle, KILL_SOCKET, 0,integer(Sender));
end;
procedure TForm1.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
memo1.lines.add(«SSError «+inttostr(ErrorCode)+» «+inttostr(integer(socket.data)));
KSocket(socket.data).free;
ErrorCode:=0;
Postmessage(Form1.Handle, KILL_SOCKET, integer(socket),0);
end;
А насчет второй ошибки, я даже не могу понять от чего она возникает, причем очень редко. Вроде бы уже принял все меры против этого…
← →
aprm_85
(2003-09-30 22:52)
[11]
А может прежде чем коннектится к хосту, проверить, есть ли Инет?
Если dial-up, все просто: TMagRAs (компонент для работы с dialup)
С выделенкой — сложнее. там возможгы варианты
← →
SergP
(2003-10-01 07:21)
[12]
> aprm_85 © (30.09.03 22:52) [11]
> А может прежде чем коннектится к хосту, проверить, есть
> ли Инет?
> Если dial-up, все просто: TMagRAs (компонент для работы
> с dialup)
> С выделенкой — сложнее. там возможгы варианты
Это ИМХО излишне. Да и как оказалось эта ошибка ловится Application.OnException как советовал Polevi. Просто я этой штукой никогда не пользовался раньше и сначала не пользовался потому, что хотел бы иметь сначала пример прежде чем использовать, но в связи с тем что примера так и никто не дал, пришлось самому экспериментировать.
← →
nikkie
(2003-10-01 13:44)
[13]
Application.OnException — это, конечно, лом, против которого нет приема. Только прибегать к нему стоит, если ты совсем сдался сделать по нормальному.
Я только что попробовал — 11001, «Windows socket error: No such host is known (11001), on API «ASync Lookup»» прекрасно ловится и гасится в OnError (по-крайней мере в D6). Ты пробовал это в тестовом приложении — один клиентский сокет на форме? Попробуй. И покажи, как ты создаешь сокет в приложении, где у тебя проблема.
← →
SergP
(2003-10-02 08:56)
[14]
2 nikkie У меня D5… Да и переходить на D6 почему-то не очень хочется. Хотя возможно что придется… Не знаю почему оно у Вас ловится в onError, но у меня ловятся там все остальные ошибки кроме 11001.
А насчет того чтобы показать как что и где я создаю — может лучше я скину исходник на мыло? А то много постить тут нужно…
← →
Digitman
(2003-10-02 09:15)
[15]
> SergP
по кр.мере в D5 отказ с кодом WSAHOST_NOT_FOUND = 11001 не может быт перехвачен в событии OnError, только — в App.OnException
этому есть вполне четкое объяснение, достаточно взглянуть в исх.текст компонента
procedure TCustomWinSocket.CMLookupComplete(var Message: TCMLookupComplete);
begin
if Message.LookupHandle = FLookupHandle then
begin
FLookupHandle := 0;
if Message.AsyncError <> 0 then
begin
Disconnect(FSocket);
raise ESocketError.CreateResFmt(@sWindowsSocketError,
[SysErrorMessage(Message.AsyncError), Message.ASyncError, "ASync Lookup"]);
end;
.....................
end;
end;
← →
Digitman
(2003-10-02 09:29)
[16]
> SergP
для того чтобы избавиться от вынужденной обработки отказа в App.OnException, необходимо явно св-ва Address и Port (т.е. явный IP-адрес и явный номер порта), оставляя св-ва Host и Service пустыми
в этом случае не будут задействованы службы, разрешающие имя хоста в его адрес и имя сервиса в номер соотв.порта
как раз эти службы, будучи задействованными при неуказании явно адреса и порта, вызывают внутри компонента ф-ции [WSAAsync]GetHostByName (хост -> адрес) и [WSAASync]GetServByName (имя сервиса -> номер порта) … именно эти ф-ции генерируют отказ с упомянутым кодом, и отказ этот обрабатывается компонентом столь нецдобно, по твоему мнению.
есть другие варианты — работать либо с блок.гнездом (тогда исключения во всех методах компонента «ловятся» банальным try..except) либо работать с неблок.гнездом, но указывать адрес+порт явно, проводя перед коннектом разрешение имен самостоятельно явными вызовами вышеупомянутых Winsock-ф-ций.
← →
nikkie
(2003-10-02 13:46)
[17]
что ж, значит, в D5 действительно нужен лом. а в D6 код такой:
procedure TCustomWinSocket.CMLookupComplete(var Message: TCMLookupComplete);
var
ErrorCode: Integer;
begin
if Message.LookupHandle = FLookupHandle then
begin
FLookupHandle := 0;
if Message.AsyncError <> 0 then
begin
ErrorCode := Message.AsyncError;
Error(Self, eeLookup, ErrorCode);
Disconnect(FSocket);
if ErrorCode <> 0 then
raise ESocketError.CreateResFmt(@sWindowsSocketError,
[SysErrorMessage(Message.AsyncError), Message.ASyncError, "ASync Lookup"]);
Exit;
end;
...
end;
end;
← →
Digitman
(2003-10-02 14:09)
[18]
> nikkie
скорее всего это был маленький недосмотр со стороны Борланда
в 6-ке его исправили
I am trying to send email using Indy 10.5.7 on C++ Builder XE but I get Host not found error. I added TIdSMTP, TIdSSLIOHandlerSocketOpenSSL and TIdMessage components. I set the host to smtp.office365.com, the port to 587 and UseTLS to utUseExplicitTLS. The username and password are set for the email address of the account I need to connect with.
I am trying to send the email using :
IdMessage1->From->Name = Name->Text;
IdMessage1->From->Address = EmailAddress->Text;
IdMessage1->Body = Msg->Lines;
try
{
IdSMTP1->Connect(1000);
try
{
IdSMTP1->Send(IdMessage1);
}
__finally
{
IdSMTP1->Disconnect();
}
}
catch (const Exception &E)
{
MessageBox(NULL, E.Message.c_str(), L"Error", MB_OK | MB_ICONERROR);
}
asked Oct 15, 2019 at 5:15
6
This line is wrong:
IdSMTP1->Connect(1000);
In Indy 9, Connect()
had an overload that accepted a timeout as input. But in Indy 10, that overload was removed, and the timeout parameter was reimplemented as a ConnectTimeout
property.
Your original code compiles because Connect()
in Indy 10 has an overload that takes a hostname String
as input, overwriting the Host
property, and (Ansi|Unicode)String
has a constructor that accepts an int
as input. Thus, your code is effectively doing this
IdSMTP1->Connect(String(1000));
Which tries to connect to a hostname named "1000"
, ignoring the "smtp.office365.com"
hostname you assigned to the Host
property. That is why you are getting socket error 11001.
You need to replace the offending line with this code instead:
//IdSMTP1->Connect(1000);
IdSMTP1->ConnectTimeout = 1000;
IdSMTP1->Connect();
answered Oct 19, 2019 at 3:46
Remy LebeauRemy Lebeau
536k30 gold badges444 silver badges750 bronze badges
asker
unread,
Jul 31, 2003, 4:50:58 PM7/31/03
to
Hi,
this is my first small own created internetprogram:
procedure TForm1.SpeedButton1Click(Sender: TObject);
var HTMLstring : string;
begin
with IdHTTP1 do
begin
host := ‘http://www.pop.com/’;
port := 80;
HTMLstring := ConnectAndGetAll;
Try
// still nothing
finally Disconnect;
end;
end;
But it doesn’t work. Always appears an (Debugger-)Exception which says:
‘Socket Error # 11001…. host not found’
Sometimes the exception also says only: Socket Error # 11004 — with no
further comment.
Where could be the mistake?
Second Question:
If i got this answered HTML-string finally (so i hope anyway *g*), how i can
show the contens like in an explorerwindow. I only have D7Personal and the
Indy-Components to solve this task.
Thanks in advance
asker
Remy Lebeau (TeamB)
unread,
Aug 1, 2003, 12:10:44 AM8/1/03
to
«asker» <1737…@gmx.net> wrote in message
news:3f29…@newsgroups.borland.com…
> ‘Socket Error # 11001…. host not found’
WSAHOST_NOT_FOUND
(11001)
Host not found.
No such host is known. The name is not an official hostname or alias, or it
cannot be found in the database(s) being queried. This error may also be
returned for protocol and service queries, and means the specified name
could not be found in the relevant database.
> with IdHTTP1 do
> begin
> host := ‘http://www.pop.com/’;
> port := 80;
> HTMLstring := ConnectAndGetAll;
> Try
> // still nothing
> finally Disconnect;
> end;
> end;
That is not the correct way to request data from an HTTP server. You should
be using the TIdHTTP::Get() method instead:
HTMLstring := IdHTTP1.Get(‘http://www.pop.com/’);
> But it doesn’t work. Always appears an (Debugger-)Exception which says:
> ‘Socket Error # 11001…. host not found’
That is because «http://www.pop.com» is not a valid host name for a TCP
connection. That is an HTTP URL, a very different issue altogether. The
correct hostname to use would have been «pop.com» instead.
> Sometimes the exception also says only: Socket Error
> # 11004 — with no further comment.
WSANO_DATA
(11004)
Valid name, no data record of requested type.
The requested name is valid and was found in the database, but it does not
have the correct associated data being resolved for. The usual example for
this is a hostname -> address translation attempt (using gethostbyname or
WSAAsyncGetHostByName) which uses the DNS (Domain Name Server), and an MX
record is returned but no A record — indicating the host itself exists, but
is not directly reachable.
Gambit
asker
unread,
Aug 1, 2003, 2:12:55 AM8/1/03
to
Thanks for your help,
connecting the host is working now.
Now, my small beginner-program looks like this:
procedure TForm1.SpeedButton1Click(Sender: TObject);
var HTMLstring : string;
begin
with IdHTTP1 do
begin
host := ‘pop.com’;
Connect;
Try
HTMLstring := Get(‘pop.com’);
// still nothing
end;
end;
But now, after connection there is another problem comes up in form of a
window which appears with the title: Sourcefile not found: IdHTTP.pas And
than it want to have the path for this file. But i don’t have such a file. 3
days ago i downloaded Indy9 and such a file wasn’t with it. What should i do
now. For what the program want to have this file?
Thanks
asker
asker
unread,
Aug 1, 2003, 2:16:10 AM8/1/03
to
Thanks for your help,
connecting the host is working now.
Now, my small beginner-program looks so:
procedure TForm1.SpeedButton1Click(Sender: TObject);
var HTMLstring : string;
begin
with IdHTTP1 do
begin
host := ‘pop.com’;
port := 80;
Connect;
Try
HTMLstring := Get(‘pop.com’);
// still nothing
finally Disconnect; // <—- this line IS existing, too
end;
end;
But now, after connection there is another problem comes up in form of a
window which appears with the title: Sourcefile not found: IdHTTP.pas And
than it want to have the path for this file. But i don’t have such a file. 3
days ago i downloaded Indy9 and such a file wasn’t with it. What should i do
now. Is there any hope for me?
Thanks
asker
asker
unread,
Aug 1, 2003, 2:57:43 AM8/1/03
to
please ignore the last 2 posts. I found this file IdHTTP.pas, of course
But now after i tell this window the path of this IdHTTP.pas — file there
appears another Dubbuger-Exception:
An EIdHTTPProtocolException with the comment: ‘HTTP/1.1 400 Bad Request’
Perhaps, do you have any idea to solve this next (small) problem too?
Thx
asker
*g*
Remy Lebeau (TeamB)
unread,
Aug 1, 2003, 4:14:52 AM8/1/03
to
news:3f299ee5$1…@newsgroups.borland.com…
> An EIdHTTPProtocolException with the comment:
> ‘HTTP/1.1 400 Bad Request’
That is because you are passing the wrong URL to Get(). See my other reply.
Gambit
Remy Lebeau (TeamB)
unread,
Aug 1, 2003, 4:13:59 AM8/1/03
to
news:3f299465$1…@newsgroups.borland.com…
> host := ‘pop.com’;
> Connect;
There is no need to set the Host or call Connect() directly. TIdHTTP::Get()
handles everything internally.
That is the wrong URL to pass to Get(). You should be passing in the full
HTTP URL, including the «http://» and «www.» portions.
Your code should look like this:
procedure TForm1.SpeedButton1Click(Sender: TObject);
var
HTMLstring : string;
begin
HTMLstring := IdHTTP1.Get(‘http://www.pop.com’);
// use HTMLstring as needed
end;
> But now, after connection there is another problem comes up in form of a
> window which appears with the title: Sourcefile not found: IdHTTP.pas
That suggests that an exception was thrown and the debugger is trying to
find IdHTTP.pas on your machine so that is can display the source code in
the editor.
> i don’t have such a file. 3 days ago i downloaded
> Indy9 and such a file wasn’t with it
Yes, it does have such a file. Indy is an open-source project, downloading
it includes the full source code, including the source for TIdHTTP.
Gambit
asker
unread,
Aug 1, 2003, 11:43:23 AM8/1/03
to
Yes, there is no Exception any more and also the string is loaded so there
is only one littel question remaining :-).
Now i also want to show this string like in an explorer-window. Do you know
a (D7Personal-) control or an Indy-Component which is able to do this? (Or
where else perhaps i can download such a component for showing these strings
in his correct way?)
Thanks a lot
asker
Remy Lebeau (TeamB)
unread,
Aug 1, 2003, 11:01:55 PM8/1/03
to
news:3f2a…@newsgroups.borland.com…
> Now i also want to show this string like in an explorer-window.
Please clearify. Do you mean that you want to actually display the HTML in
a browser window? If so, then Indy is not the right solution for you.
Borland has a TCppWebBrowser component for that instead. Or you can import
the IE ActiveX control manually.
Gambit
asker
unread,
Aug 1, 2003, 11:42:29 PM8/1/03
to
Yes, i intend also to display this got stuff in a browser window like the
Internet-Explorer itself do it. Unfortunatly i only have D7Personal and
therefore i cannot use this Borlands WebBrowser. But i have a little
experience in api-functions so perhaps its possible to realize my intentions
about installing the IE ActiveX control manually. I will google after that
keyword at once… *g*
Thanks a lot once more
asker
Remy Lebeau (TeamB)
unread,
Aug 2, 2003, 2:39:13 AM8/2/03
to
news:3f2ac2a3$1…@newsgroups.borland.com…
> i have a little experience in api-functions so perhaps
> its possible to realize my intentions about installing the
> IE ActiveX control manually.
The IDE has an «Import ActiveX Control» option in its menu.
Gambit
asker
unread,
Aug 2, 2003, 3:48:42 AM8/2/03
to
Thanks,
accordingly your good advice with the IDE i installed the
Microsoft Active Plugin (Version 1.0).
But during that Delphi warned me because this line (139):
property dispatch: IDispatch index -1 read GetIDispatchProp;
would hide a Member of the basic-Class??? What does it mean, is it very
important or should i ignore it?
And still this:-) Before i start a first run with this plugin-component, i
have to find a good second parameter for the Load-method i want to use:
procedure Load(const bstrUrl: WideString; bDeleteRegistry: SYSINT);
In ‘bstrUrl’ i will load the got string (form IdHTTP1.get()), but what
should i use for the second parameter: ‘bDeleteRegistry’ ? What would be a
useful value for it?
Thanks
asker
Remy Lebeau (TeamB)
unread,
Aug 2, 2003, 4:58:42 AM8/2/03
to
news:3f2afc57$1…@newsgroups.borland.com…
> accordingly your good advice with the IDE i installed
> the Microsoft Active Plugin (Version 1.0).
That is not the web browser control, nor is that the specific control I
mentioned (i didn’t explitically mention any). The correct control that you
should have imported is «Microsoft Internet Controls» instead. There may be
another one, but its name escapes me at the moment
Gambit
asker
unread,
Aug 2, 2003, 6:03:48 AM8/2/03
to
YES, the WebBrowser is working ! Great !!!
Without your help, i surely would have given up.
So at all events: Thank you very much for this!
…it’s a good beginning for more in that direction !!!!
YEEEAAAAAAHHHHHHHHHHHHHHHH *ggg*
(But that will start a little bit later *g*)
asker
При работе с сокетами бывают исключительные ситуации, при которых возникают ошибки с некими кодами. Немножко поискав — нашел описание ошибок. Решил привести данное описание в своем блоге:
Socket error 10004 — Interrupted function call
Socket error 10013 — Permission denied
Socket error 10014 — Bad address
Socket error 10022 — Invalid argument
Socket error 10024 — Too many open files
Socket error 10035 — Resource temporarily unavailable
Socket error 10036 — Operation now in progress
Socket error 10037 — Operation already in progress
Socket error 10038 — Socket operation on non-socket
Socket error 10039 — Destination address required
Socket error 10040 — Message too long
Socket error 10041 — Protocol wrong type for socket
Socket error 10042 — Bad protocol option
Socket error 10043 — Protocol not supported
Socket error 10044 — Socket type not supported
Socket error 10045 — Operation not supported
Socket error 10046 — Protocol family not supported
Socket error 10047 — Address family not supported by protocol family
Socket error 10048 — Address already in use
Socket error 10049 — Cannot assign requested address
Socket error 10050 — Network is down
Socket error 10051 — Network is unreachable
Socket error 10052 — Network dropped connection on reset
Socket error 10053 — Software caused connection abort
Socket error 10054 — Connection reset by peer
Socket error 10055 — No buffer space available
Socket error 10056 — Socket is already connected
Socket error 10057 — Socket is not connected
Socket error 10058 — Cannot send after socket shutdown
Socket error 10060 — Connection timed out
Socket error 10061 — Connection refused
Socket error 10064 — Host is down
Socket error 10065 — No route to host
Socket error 10067 — Too many processes
Socket error 10091 — Network subsystem is unavailable
Socket error 10092 — WINSOCK.DLL version out of range
Socket error 10093 — Successful WSAStartup not yet performed
Socket error 10094 — Graceful shutdown in progress
Socket error 11001 — Host not found
Socket error 11002 — Non-authoritative host not found
Socket error 11003 — This is a non-recoverable error
Socket error 11004 — Valid name, no data record of requested type
Posts: 3
Threads: 1
Joined: Jan 2021
Reputation:
0
Hi,
A confession first: I’ve never been playing too much with Indy, so my knowledge is limited to simple tasks.
A task is to send a Get request to a web page (actually an ASP.NET AXD HttpHandler) and receive some response back.
As simple code as:
Code:
var
idHTTP : TIdHTTP;
response : TStringStream;
begin
response := TStringStream.Create('');
idHTTP := TIdHTTP.Create(nil);
try
try
idHTTP.Get('http://mywebsite.com/MyHandler.axd?id=123', response);
if idHTTP.ResponseCode = 200 then
//log ok
else
//log not ok
;
except on E : Exception do
//log exception
end;
finally
idHTTP.Free;
response.Free;
end;
end;
For most users this works — response is received.
For some users, the following error is returned «Socket Error # 11001. Host not found.«. I suspect it has to do with proxy they are using.
What options do I have to let those «socket error» users specify some more parameters and be able to receive response?
-žarko
Posts: 1,136
Threads: 37
Joined: Mar 2018
Reputation:
30
Location: Limassol, Cyprus
Host not found means that the server isnt available or reachable from that client location. If they are using a proxy, then it might be blocking that due to firewall policy, or that a proxy is required and you are not using the proxy. For HTTP most proxies are transparent, but some places still use the very old SOCKS or HTTP proxy in which you have to tell Indy to use them and need the proxy info from the user.
Posts: 3
Threads: 1
Joined: Jan 2021
Reputation:
0
(01-15-2021, 04:32 PM)kudzu Wrote: For HTTP most proxies are transparent, but some places still use the very old SOCKS or HTTP proxy in which you have to tell Indy to use them and need the proxy info from the user.
So, would it be enough to let them specify values for the IDHTTP’s ProxyParams property (TIdProxyConnectionInfo) ?
Or if not, what exactly is meant by «or that a proxy is required and you are not using the proxy«?
p.s.
I asked and they said they are using a proxy — but nothing more (waiting for more info).
-ž
Posts: 1,136
Threads: 37
Joined: Mar 2018
Reputation:
30
Location: Limassol, Cyprus
You need to first know what type of proxy they are using. SOCKS and HTTP proxies are handled differently. Amazing that anyone is still using these non transparent proxies in 2021.. but some still are.
Posts: 550
Threads: 1
Joined: Mar 2018
Reputation:
33
Location: USA
(01-15-2021, 04:45 PM)zarkogajic Wrote: So, would it be enough to let them specify values for the IDHTTP’s ProxyParams property (TIdProxyConnectionInfo) ?
If they are using an HTTP proxy, then yes.
But if they are using a SOCKS proxy, then you will have to assign a TIdIOHandlerStack component (for non-HTTPS requests) or TIdSSLIOHandlerSocketBase-derived component like TIdSSLIOHandlerSocketOpenSSL (for HTTPS requests) to the TIdIOHandler.IOHandler property, and then you can assign a TIdSocksInfo component to the TIdHTTP.IOHandler.TransparentProxy property.
This same technique can also be used for HTTP proxies, replacing TIdSocksInfo with TIdConnectThroughHttpProxy (but I would not recommend doing that for TIdHTTP, since it has its own built-in HTTP proxy support).
Posts: 3
Threads: 1
Joined: Jan 2021
Reputation:
0
Thanks Remy.
Ok, I’m allowing them to specify ProxyPassword, ProxyPort, ProxyServer and ProxyUsername (properties for TIdProxyConnectionInfo). So, we’ll see when they come back after trying to make it work…
There’s also a boolean property «BasicAuthentication» — what is this one used for?
-žarko
Posts: 550
Threads: 1
Joined: Mar 2018
Reputation:
33
Location: USA
01-19-2021, 07:01 PM
(This post was last modified: 01-19-2021, 07:03 PM by rlebeau.)
(01-18-2021, 09:43 AM)zarkogajic Wrote: There’s also a boolean property «BasicAuthentication» — what is this one used for?
When TIdHTTP receives a response from an HTTP proxy/server asking for authentication credentials, the proxy/server specifies the authentication schemes it supports (BASIC, DIGEST, NTLM, etc). TIdHTTP then checks the currently registered classes in any IdAuthentication… units you have in your uses clause, looking for a class to handle a supported authentication scheme. It then fires the OnSelect(Proxy)Authorization and On(Proxy)Authorization events to let you override any decisions TIdHTTP made, if needed, before a new authentication request is sent back to the proxy/server.
When logging in to an HTTP proxy, the ProxyParams.BasicAuthentication property simply tells TIdHTTP whether or not it is allowed to fallback to the BASIC authentication scheme if another scheme is not used.
When logging in to an HTTP server, the Request.BasicAuthentication property does the same thing.