Windows socket error 10049 api connect

Windows socket error 10049 api connect

Подскажите пожайлуста, вот сделал одну форму занес на нее сервер сокет и кнопку, поле мемо еще, на событие он клик кнопки
procedure TForm1.Button1Click(Sender: TObject);
begin
serverSocket1.active:=true;
edit1.text:=»Active»;
end;
на событие OnClientRead:
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
if Socket.ReceiveText =»r» then
edit1.text:=»Conect complete»;
end;
на событие Дестрой формы:
procedure TForm1.FormDestroy(Sender: TObject);
begin
ServerSocket1.active:=false;
end;
Порт выставил 3333

Потом сделал клиента на него кинул кнопку, на онклик кнопки клиента :
procedure TForm1.Button1Click(Sender: TObject);
begin
clientsocket1.active:=true;
clientsocket1.socket.sendtext(«r»);
clientsocket1.active:=false;
end;
в host написал: 127.0.0.1 и порт выставил:3333
ну и запускаю ето все дело а оно мне: Windows socket error: (10049), on API «connect»


TButton ( 2003-10-16 04:45 ) [1]

на БатонКлик
client.Socket.Open;

на ClientSocketConnect
clientSocket.Socket.SendText(«r»);
clientSocket.Close;


Digitman ( 2003-10-16 08:42 ) [2]

Specifies an alias for the IP address of the server system.

property Host: string;

Host is a string containing the domain name and service of a particular system, such as

For client sockets, set Host to the system with which the client socket should form a connection. When the socket opens a connection, it looks up the IP address for the server socket using the value of Host.

Some servers change the system or IP address that is associated with a particular host name. Using a host name allows the client socket to find the abstract site represented by the host name, even when it has moved to a new IP address.

If Host is set, it takes precedence over the Address property when looking up the address of the server.


qqqqq0001 ( 2003-10-16 13:07 ) [3]

procedure TForm1.Button1Click(Sender: TObject);
begin
clientsocket1.open;
end;
ну и при нажатии на кнопку снова выдает Windows socket error: (10049), on API «connect»


qqqqq0001 ( 2003-10-16 13:08 ) [4]

вот полный текст всего что есть в килиенте

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
ClientSocket1: TClientSocket;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
private
< Private declarations >
public
< Public declarations >
end;

var
Form1: TForm1;

procedure TForm1.Button1Click(Sender: TObject);
begin
clientsocket1.open;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
clientsocket1.active:=false;
end;

procedure TForm1.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
clientsocket1.socket.SendText(«r»);
clientsocket1.close;
end;

ему про фому, он — все про ерему свое гнет)

для кого фрагмент хэлпа был приведен ? для Пушкина ?
ты вчитался в него, вник ?

Читайте также:  Аналоги автокада для linux


qqqqq0001 ( 2003-10-16 17:28 ) [6]

Дак я не понял мне что вместо 127.0.0.1 Localhost чтоли написать
или в adress 127.0.0.1 добавить ну счас попробую


qqqqq0001 ( 2003-10-16 17:37 ) [7]

Ну вот адресу присвоил свойство едита текст, откомпилировал, запустил сервер, потом клиент запустил, в едите клиента ввел все те же злополучные 127,0,0,1 и теперь мне выдает — Asynchronous socket error 10061


Digitman ( 2003-10-17 08:15 ) [8]

ну вот видишь ! уже и отказ совсем другой) . значит, интерфейс сервера локализован , но сервер не активен в это момент


qqqqq0001 ( 2003-10-17 22:08 ) [9]

Такс вобщем думал что делать ну и решил выставить(так просто ради интереса) Server Type & Client Type = stNonBlocking(интересно а что ето значит?) теперь никаких ошибок не выдает но на прием тексат от клиента сервер все равно никак не реагирует

Поработай пока с режимом stBloking. Это проще. Потом, если надо будет,перейдешь на другой.


Digitman ( 2003-10-20 14:33 ) [11]

Specifies whether the client socket reads and writes information asynchronously over the socket connection.

type TClientType = (ctNonBlocking, ctBlocking);
property ClientType: TClientType;

Set ClientType to ctNonBlocking to enable the client socket to respond to asynchronous reading and writing events. When ClientType is ctNonBlocking, execution is not blocked by reading and writing over the socket connection. OnRead or OnWrite events occur when the socket needs to read or write over the connection.

Set ClientType to ctBlocking to force all reading and writing to occur synchronously. It is a good idea to include the client socket object in a thread if the ClientType is ctBlocking, so that I/O does not block all execution within the client application.

When ClientType is ctBlocking, use a TWinSocketStream object for reading and writing. TWinSocketStream prevents the application from hanging indefinitely if a problem occurs while reading or writing. It also can wait for the socket connection to indicate its readiness for reading.

Ошибка Winsock 10049 пытается связать

У меня проблема с подключением к серверу. При попытке привязать сервер к IP-адресу моего внешнего устройства я получил ошибку winsock: 10049 Невозможно назначить запрошенный адрес. Использование локального сервера работает правильно.
Этот IP-адрес: 192.168.0.202 пинг успешно.
Я работал на win8.1. Я отключил брандмауэр и Windows Defender, и это не помогло.

Решение

bind() Функция используется для указания того, какой адрес серверной системы используется для приема соединений от удаленных клиентов, а не для указания, какому удаленному клиенту разрешено подключаться к серверу. bind() Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.

Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.

Читайте также:  Сколько времени запущена windows

В общем, вы хотите использовать INADDR_ANY если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.

Другие решения

Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError всякий раз, когда приложение пытается связаться с неверным IP-адресом.

привязка к определенному IP-адресу означает, что всякий раз, когда вы запускаете программу (сервер), адрес должен быть действительным (доступным), но, тем не менее, DHCP выдает вам динамические IP-адреса каждый раз, когда вы отключаете / подключаете адаптер, так что вы адрес, который вы связывали с сервером в прошлый раз недопустимо исправить его, откройте cmd и введите:

вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY так что вы позволяете системе делать работу за вас.

вам нужно только с клиента ввести адрес сервера и порт и подключиться.

bind() fails with windows socket error 10049

I try to make a client/server program in C with IPv6 and UDP. When the program binds the socket it return the WSAError 10049. I know that this is a problem with the adress name but don’t see whats the problem. I hope someone can help.

4 Answers 4

You should use PF_INET here instead of AF_INET . They have the same value, but you’re not specifying an address family AF here, you’re specifying a protocol family PF . This is just a style recommendation.

I would suggest to memset zero the below arrays,structures:

Before you can use the sockaddr_in6 struct, you will have to memset it to zero:

The reason is that the struct sockaddr_in6 structure contains other fields which you are not initializing (such as sin6_scope_id ) and which might contain garbage.

I have faced the same error.

@askMish ‘s answer is quite right.I didn’t understand it at the first place,however I find it out eventually.

This normally results from an attempt to bind to an address that is not valid for the local computer..

Normally we have our computer under some gateway.

If we run ipconfig we will find the IP address is 192.168.something.

So that’s the IP we could use to bind in code.

While other should connect with the public IP(if you can surf Internet you have one for sure.) like 47.93.something if they are in the same LAN with you.

You need to find that IP at your gateway(possibly your family’s route).

Читайте также:  Windows aero не работает что делать

I had that same error code when calling bind() under windows.

The reason in my case was not the same as in the initial poster’s code, but i guess other will have made the very same mistake as me:

I generated the local address on which i want the server to be bound locally using the inet_addr() -function. I assigned this result to the local address structure struct sockaddr_in localaddr this way:

But inet_addr() already returns the address in byte-network-order, so the call htonl(inaddr) was wrong in my code and caused error 10049:

When calling bind() using «all local interfaces» ( INADDR_ANY ) it worked, because of this coincidence INADDR_ANY == htonl(INADDR_ANY) :

winsock: connect fails with error 10049 when using localhost (127.0.0.1)

i wrote a class encapsulating some of the winsock functions to imitate a simple TCP socket for my needs.

When i try to run a simple connect-and-send-data-to-server test the «client» fails on its call to connect with the error code of 10049 (WSAEADDRNOTAVAIL) connect function on MSDN

What I am doing is (code below): Server:

  1. Create a Server Socket -> Bind it to Port 12345
  2. Put the Socket in listen mode
  3. Call accept

Client

  1. Create a socket -> Bind it to a random port
  2. Call Connect: connect to localhost, port 12345

=> the call to connect fails with Error 10049, as described above

Here is the main function including the «server»:

Client thread function

The Connect-Function

Additional Information: -Incgetaddrinfo is a function object encapuslating getaddrinfo. -Noone of the server functions return any error and work as expected when stepping through them using the debugger or when letting them run solely.

I’d be glad to hear your suggestions what the rpoblem might be.

Edit: It works when I dont connect to («localhost»,»12345″) , but to («»,12345) . When look into the address resolution process of getaddrinfo it gives 127.0.0.1 for «localhost» and my real IP for «»

Windows socket error 10049 api connect

Уважаемые Мастера! У меня к Вам такой жизненый вопрос: при попытке соединения обычного компонента ClientSocket выдает ошибку
«Windows socket error:(10049), on API connect» — я не могу соединиться ни с кем. Что сделать, чтобы она пропала или как ее обойти?

Заранее огромное спасибо!! С уважением Александр


gavrila © ( 2004-02-10 19:57 ) [1]

Посмотри здесь описание ошибки, может поможет (правда на инглиш)
http://ssz.by.ru/programming/different/sockerrors.htm


Manulo © ( 2004-02-10 20:01 ) [2]


SergP © ( 2004-02-10 21:51 ) [3]

Жмем волшебную кнопку F1 и после нескоьких секунд поиска находим:

10049 Address is not available from the local machine.

ну и делаем соответствующие выводы, и правим свой код.

Оцените статью