Windows socket error 10049 on 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;
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;
ему про фому, он — все про ерему свое гнет)
для кого фрагмент хэлпа был приведен ? для Пушкина ?
ты вчитался в него, вник ?

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() Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.
Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.
В общем, вы хотите использовать INADDR_ANY если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.
Другие решения
Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError всякий раз, когда приложение пытается связаться с неверным IP-адресом.
привязка к определенному IP-адресу означает, что всякий раз, когда вы запускаете программу (сервер), адрес должен быть действительным (доступным), но, тем не менее, DHCP выдает вам динамические IP-адреса каждый раз, когда вы отключаете / подключаете адаптер, так что вы адрес, который вы связывали с сервером в прошлый раз недопустимо исправить его, откройте cmd и введите:
вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY так что вы позволяете системе делать работу за вас.
вам нужно только с клиента ввести адрес сервера и порт и подключиться.
Getting error 10049 (address not avai) on sendto() in UDP connection, but bind() worked
EDIT #2: The problem was I stupidly had the memset parameter order backwards, so, I wasn’t zero’ing out my structure and thus must have had some garbage values in some of the rarely used fields. Which presumably explains why it initially worked on my system but not on the customer. I don’t think I even got a compiler warning on it.
EDIT #1: Remy suggested I use InetNtop instead of my own little ipv6rev() function to print out the IPv6 address. I did that and got basically the same results. His next suggestion is to build a SSCCE which I will work on. But, for the moment, I am just editing this to note the use if InetNtop().
The application I am writing is sort-of a software router, where I get data on one socket (which happens to be IPv4) and send it out another on IPv6 UDP. I had it working on my machine, but, when I installed my application at customer, the sendto calls fail. I was initially communicating with another machine, but, to make the test as simple as possible, I put the UPD IPv6 receiver on the same machine, with its own IP. Using netstat, I seem to see that I’ve bound properly:
«NATerator» being my software router application, and the receiver being a Java app (node.exe) So, they are both bound to port 20000, but to different IP addresses. So, presumably, I should be able to send from . 104 to . fff0 I would think.
But the sendto() fails with 10049. Which seems to indicate that I’m sending to a bad IP address or port for the socket. So, I added debug message to print out the IP address and port and it looks like I am sending to the right address. The debug message prints out:
Here is the code for the debug message before sendto, then the call to sendto and the debug after it:
Note that «cpu_debug» is an inhouse debug logger that operates like printf().
The code where I initially open the socket is here. I don’t currently set any socket options. Not sure I need any. I just call socket() and bind() like so:
The lookupHost function gets fills in the in6_addr structure, which I think has to be working, since nestat shows the application bound. The «rtuport» is defined as 20000. I should have made the name in all caps since it is a #define constant. So, the creation of the socket() and bind() calls look like the work. But perhaps I need some socket options set?
At any rate, the last piece of relevant code is where I fill in the «to» structure. It is defined as:
I have a function that populates to:
Where rtu_to_ipv6_map is defined as follows:
And, I’m reasonably confident that the value in that array is the correct address because I unpack it back out in the debug message, and it correctly states the destination address.
So, perhaps I am overlooking something simple. But, as near as I can see, I have the socket open, I’m sending to an available and reasonable IP address. (I can ping both IP addresses. So it should work, but it doesn’t. Any idea what I might be missing? And if it is stupid of me, maybe not downvote me too bad, LOL.
Oh, I might as well list the output from IPconfig:
PS. I’m not a expert socket programmer. But, I have written a few socket related apps, with some previous help from this site. But, I know that there is much I don’t know. Thanks for any help!

