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:
- Create a Server Socket -> Bind it to Port 12345
- Put the Socket in listen mode
- Call accept
Client
- Create a socket -> Bind it to a random port
- 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»:
HANDLE hThread = NULL;
Inc::CSocketTCP ServerSock;
Inc::CSocketTCP ClientSock;
try
{
ServerSock.Bind(L"", L"12345");
ServerSock.Listen(10);
//Spawn the senders-thread
hThread = (HANDLE)_beginthreadex(nullptr, 0, Procy, nullptr, 0, nullptr);
//accept
ServerSock.Accept(ClientSock);
//Adjust the maximum packet size
ClientSock.SetPacketSize(100);
//receive data
std::wstring Data;
ClientSock.Receive(Data);
std::wcout << "Received:t" << Data << std::endl;
}
catch(std::exception& e)
{...
Client thread function
unsigned int WINAPI Procy(void* p)
{
Sleep(1500);
try{
Inc::CSocketTCP SenderSock;
SenderSock.Bind(L"", L"123456");
SenderSock.Connect(L"localhost", L"12345");
//Adjust packet size
SenderSock.SetPacketSize(100);
//Send Data
std::wstring Data = L"Hello Bello!";
SenderSock.Send(Data);
}
catch(std::exception& e)
{
std::wcout << e.what() << std::endl;
}...
The Connect-Function
int Inc::CSocketTCP::Connect(const std::wstring& IP, const std::wstring& Port)
{
//NOTE: assert that the socket is valid
assert(m_Socket != INVALID_SOCKET);
//for debuggin: convert WStringToString here
std::string strIP = WStringToString(IP), strPort = WStringToString(Port);
Incgetaddrinfo AddyResolver;
addrinfo hints = {}, *pFinal = nullptr;
hints.ai_family = AF_INET;
//resolve the ip/port-combination for the connection process
INT Ret = AddyResolver(strIP.c_str(), strPort.c_str(), &hints, &pFinal);
if(Ret)
{
//error handling: throw an error description
std::string ErrorString("Resolving Process failed (Connect): ");
ErrorString.append(Inc::NumberToString<INT>(Ret));
throw(std::runtime_error(ErrorString.c_str()));
}
/*---for debbuging---*/
sockaddr_in *pP = (sockaddr_in*)(pFinal->ai_addr);
u_short Porty = ntohs(pP->sin_port);
char AddBuffer[20] = "";
InetNtopA(AF_INET, (PVOID)&pP->sin_addr, AddBuffer, 20);
/*--------------------------------------------------------*/
if(connect(m_Socket, pFinal->ai_addr, pFinal->ai_addrlen) == SOCKET_ERROR)
{
int ErrorCode = WSAGetLastError();
if((ErrorCode == WSAETIMEDOUT) || (ErrorCode == WSAEHOSTUNREACH) || (ErrorCode == WSAENETUNREACH))
{
//Just Unreachable
return TCP_TARGETUNREACHABLE;
}
//real errors now
std::string ErrorString("Connection Process failed: ");
ErrorString.append(Inc::NumberToString<int>(ErrorCode));
throw(std::runtime_error(ErrorString.c_str()));
}
return TCP_SUCCESS;
}
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 ""
Why doesn’t it work with my loopback-IP?
- Remove From My Forums
-
Question
-
I’m trying to control the network interface used for a web service call by setting the local endpoint. The error I’m getting indicates that the local IP Address that isn’t recognised by the machine. The local address I’m using is returned by ipconfig
and to make sure I also ran the following code snippet (simplified down to the TCP level):foreach(
NetworkInterfaceadapter
inNetworkInterface.GetAllNetworkInterfaces()
) {IPAddressaddr = adapter.GetIPProperties().UnicastAddresses[0].Address;
IPEndPointlocalEp =
newIPEndPoint(addr,
60000);IPEndPointremote =
newIPEndPoint(IPAddress.Parse(«192.168.203.26»),
8080);TcpClientlocal =
newTcpClient(localEp);local.Connect(remote);
local.Close();
}
There is only one adapter with one IP Address and the port is not in use according to netstat.
If I don’t bind the client to a local endpoint the connection is OK so the remote endpoint is reachable.
Am I missing something subtle here?
Its hard to believe that something so fundamental is broken.
Answers
-
Hi David,
I use your code to test, but I encounter another issue when “using IPEndPoint localEp = new IPEndPoint(addr, 60000);”. Can you post a whole test project to me for reproduce?
>If I don’t bind the client to a local endpoint the connection is OK so the remote endpoint is reachable.
That works for me as well, so I assume there is something configuration about the firewall. Maybe you can test it on your side and let me know the result.
Regards,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click
<a href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.-
Marked as answer by
Monday, July 28, 2014 1:36 AM
-
Marked as answer by
- Remove From My Forums
-
Question
-
We had FONT issues within XP virtual mode on a MS Win 7 64 box. The program ran fine under the original install of virtual PC install and the install of our app. With the re-install, we get the following error while running the app:
Windows Socket Error- The request address is not valid in its connection(10049), on API connect.
This seems to be the case with all of our customers. The 1st install runs fine, but after the re-install, this is what we get. I have too much to try to repair to mention here, including registry fixes and reinstall of XP Virtual Machine.
Is there a fix for this?Thanks/Pete
Answers
-
Hi,
By default, win7 has windows virtual PC installed, and Windows XP Mode and Windows Virtual PC are two different things.
(Windows Virtual PC is the latest Microsoft virtualization technology. It is just a support platform that you can use it to run more than one operating system at the same time on one computer, and to run many productivity applications
on a virtual Windows environment, with a single click, directly from a computer running Windows 7.)Please refer to:
Install and use Windows XP Mode in Windows 7
http://windows.microsoft.com/en-US/windows7/install-and-use-windows-xp-mode-in-windows-7
And regarding to the App, I suggest you reinstall it for a test, or reinstall it in your host PC rather than VM XP for a test.
Regards,
Yolanda
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place.
-
Marked as answer by
Monday, October 28, 2013 3:34 PM
-
Marked as answer by
У меня проблема с подключением к серверу. При попытке привязать сервер к IP-адресу моего внешнего устройства я получил ошибку winsock: 10049 Невозможно назначить запрошенный адрес. Использование локального сервера работает правильно.
Этот IP-адрес: 192.168.0.202 пинг успешно.
Я работал на win8.1. Я отключил брандмауэр и Windows Defender, и это не помогло.
Код с серверной реализацией взят из http://www.planetchili.net/forum/viewtopic.php?f=3&т = 3433
#include "Server.h"
Server::Server(int PORT, bool BroadcastPublically) //Port = port to broadcast on. BroadcastPublically = false if server is not open to the public (people outside of your router), true = server is open to everyone (assumes that the port is properly forwarded on router settings)
{
//Winsock Startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
{
MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}addr.sin_addr.s_addr = inet_addr("192.168.0.202");
addr.sin_port = htons(1234); //Port
addr.sin_family = AF_INET; //IPv4 Socket
sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
{
std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections, if we fail to listen on listening socket...
{
std::string ErrorMsg = "Failed to listen on listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
serverptr = this;
}
bool Server::ListenForNewConnection()
{
SOCKET newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
if (newConnection == 0) //If accepting the client connection failed
{
std::cout << "Failed to accept the client's connection." << std::endl;
return false;
}
else //If client connection properly accepted
{
std::cout << "Client Connected! ID:" << TotalConnections << std::endl;
Connections[TotalConnections] = newConnection; //Set socket in array to be the newest connection before creating the thread to handle this client's socket.
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(TotalConnections), NULL, NULL); //Create Thread to handle this client. The index in the socket array for this thread is the value (i).
//std::string MOTD = "MOTD: Welcome! This is the message of the day!.";
//SendString(TotalConnections, MOTD);
TotalConnections += 1; //Incremenent total # of clients that have connected
return true;
}
}
bool Server::ProcessPacket(int ID, Packet _packettype)
{
switch (_packettype)
{
case P_ChatMessage: //Packet Type: chat message
{
std::string Message; //string to store our message we received
if (!GetString(ID, Message)) //Get the chat message and store it in variable: Message
return false; //If we do not properly get the chat message, return false
//Next we need to send the message out to each user
for (int i = 0; i < TotalConnections; i++)
{
if (i == ID) //If connection is the user who sent the message...
continue;//Skip to the next user since there is no purpose in sending the message back to the user who sent it.
if (!SendString(i, Message)) //Send message to connection at index i, if message fails to be sent...
{
std::cout << "Failed to send message from client ID: " << ID << " to client ID: " << i << std::endl;
}
}
//std::cout << "Processed chat message packet from user ID: " << ID << std::endl;
if(Message == "go")
std::cout << "MESSAGE:GO!" << std::endl;
else if(Message == "left")
std::cout << "MESSAGE: GO LEFT!" << std::endl;
else if (Message == "right")
std::cout << "MESSAGE:GO RIGHT!" << std::endl;
else
std::cout << "MESSAGE:DO NOTHING!" << std::endl;
break;
}
default: //If packet type is not accounted for
{
std::cout << "Unrecognized packet: " << _packettype << std::endl; //Display that packet was not found
break;
}
}
return true;
}
void Server::ClientHandlerThread(int ID) //ID = the index in the SOCKET Connections array
{
Packet PacketType;
while (true)
{
if (!serverptr->GetPacketType(ID, PacketType)) //Get packet type
break; //If there is an issue getting the packet type, exit this loop
if (!serverptr->ProcessPacket(ID, PacketType)) //Process packet (packet type)
break; //If there is an issue processing the packet, exit this loop
}
std::cout << "Lost connection to client ID: " << ID << std::endl;
closesocket(serverptr->Connections[ID]);
return;
}
Есть идеи?
0
Решение
bind()
Функция используется для указания того, какой адрес серверной системы используется для приема соединений от удаленных клиентов, а не для указания, какому удаленному клиенту разрешено подключаться к серверу. bind()
Функция может использоваться только с адресами, которые действительны для самого сервера, но не для адресов удаленных устройств или хостов.
Чтобы определить, какому удаленному хосту разрешено подключаться к вашему серверу, вам необходимо принять подключение и подтвердить удаленный адрес в это время. Если адрес не правильный, соединение закрывается.
В общем, вы хотите использовать INADDR_ANY
если ваш сервер не является многодомным (более одного физического подключения к нескольким сетям), и только тогда, если вы пытаетесь ограничить подключения к одной из сетей, к которым подключен ваш сервер.
3
Другие решения
Winsock возвращает флаг ошибки 10049 (WSAEADDRNOTAVAIL) через свой API WSAGetLastError
всякий раз, когда приложение пытается связаться с неверным IP-адресом.
привязка к определенному IP-адресу означает, что всякий раз, когда вы запускаете программу (сервер), адрес должен быть действительным (доступным), но, тем не менее, DHCP выдает вам динамические IP-адреса каждый раз, когда вы отключаете / подключаете адаптер, так что вы адрес, который вы связывали с сервером в прошлый раз недопустимо исправить его, откройте cmd и введите:
ipconfig
вы получите список адресов ip4 / ip6, затем вы можете выбрать один из них и привязать свой сервер, однако этот метод действительно скучный, поэтому альтернативой является привязка к INADDR_ANY
так что вы позволяете системе делать работу за вас.
вам нужно только с клиента ввести адрес сервера и порт и подключиться.
0
Содержание
- bind() fails with windows socket error 10049
- 4 Answers 4
- Ошибка Winsock 10049 пытается связать
- Решение
- Другие решения
- Socket UDP from local computer, Error code 10049
- 2 Answers 2
- Windows socket error code 10049
- Socket Error Перечисление
- Определение
- Комментарии
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
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).
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:
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 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 так что вы позволяете системе делать работу за вас.
вам нужно только с клиента ввести адрес сервера и порт и подключиться.
Источник
Socket UDP from local computer, Error code 10049
i have been searching the web for a solution, but no luck.
We are making a socket, that can send and recieve data. Both the client and server version are acting as a client and server. The problem is, that the client server version ip is on a network that use NAT, which means, that when the server is trying to recieve the message, it wont, because the server have the public ip and we cant seem to find a solution, for how to recieve the data.
The SetIPProtectionLevel is Unrestricted, so it should work.
Thanks for the help.
We have tried to change the ip on the server version to local and then send from client to public server ip, but with no luck.
From local client ip to local server ip it is working.
2 Answers 2
There’s no reason this should give you any problems, provided that one side is not behind NAT and the side that’s behind NAT sends the first packet. Just follow these rules:
1) On the server, check the list of all IP addresses the host has. Bind a UDP socket to each IP address. You can skip this if the server only has one public IP address and that’s the only address it will be reached on.
2) Send a UDP reply on precisely the same socket you received the request on. This is critical to ensure the source address of the reply matches the destination address.
3) Send the UDP reply to precisely the same IP address and port as you received the query on. Ignore anything the other end says about what it thinks its IP address is or what port it thinks it’s sending from.
By «the server», I mean the side that’s not behind NAT. If you have no distinction between client and server, then follow the server rules for both sides and you’ll be fine.
These rules apply whether or not a packet is, strictly speaking, a reply. They apply to any packet you expect to get to the other side.
Remember, you can’t rely on the IP/port information in the packet to tell you who the packet came from, because NAT can change it. So you will have to put sufficient information in the payload of the datagram to do that. Ideally, expect that an endpoint’s IP/port can change at any time and send all packets to the IP/port from which you last received a packet from that particular client.
Источник
Windows socket error code 10049
Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004
Репутация: нет
Всего: нет
Эксперт
Профиль
Группа: Участник Клуба
Сообщений: 8564
Регистрация: 24.6.2003
Где: Europe::Ukraine:: Kiev
Репутация: 5
Всего: 98
Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004
Репутация: нет
Всего: нет
Эксперт
Профиль
Группа: Модератор
Сообщений: 11363
Регистрация: 13.10.2004
Где: Питер
Репутация: 53
Всего: 484
Цитата |
10049 Невозможно использовать запрошенный адрес для привязки в порту |
Попробуй просто обычным телнетом подключиться.
Проверь, пингуется ли сервер, не мешают ли файрволы и т.п.
Что за ошибка 10049:
Цитата |
WinSock Error Descriptions WSAEADDRNOTAVAIL (10049) Cannot assign requested address. Berkeley description: Normally results from an attempt to create a socket with an address not on this machine. WinSock description: Partly the same as Berkeley. The «address» it refers to is the remote socket name (protocol, port and address). This error occurs when the sin_port value is zero in a sockaddr_in structure for connect() or sendto(). In Berkeley, this error also occurs when you are trying to name the local socket (assign local address and port number) with bind(), but Windows Sockets doesn’t ascribe this error to bind(), for some unknown reason. Developer suggestions: Assume bind() will fail with this error. Let the network system assign the default local IP address by referencing INADDR_ANY in the sin_addr field of a sockaddr_in structure input to bind(). Alternately, you can get the local IP address by calling gethostname() followed by gethostbyname(). |
спроси у яндеска «Socket error 10049».
Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004
Репутация: нет
Всего: нет
Брутальный буратина
Профиль
Группа: Участник Клуба
Сообщений: 3497
Регистрация: 31.3.2002
Где: Лес
Репутация: 10
Всего: 115
Эксперт
Профиль
Группа: Модератор
Сообщений: 11363
Регистрация: 13.10.2004
Где: Питер
Репутация: 53
Всего: 484
Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004
Репутация: нет
Всего: нет
sceloglauxalbifacies
Профиль
Группа: Экс. модератор
Сообщений: 2929
Регистрация: 16.6.2006
Репутация: 5
Всего: 158
1. Публиковать ссылки на вскрытые компоненты
2. Обсуждать взлом компонентов и делится вскрытыми компонентами
Если Вам помогли и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, Snowy, Poseidon, MetalFan.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | Delphi: Сети | Следующая тема » |
[ Время генерации скрипта: 0.1200 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Источник
Socket Error Перечисление
Определение
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет коды ошибок для класса Socket.
Предпринята попытка получить доступ к объекту Socket способом, запрещенным его правами доступа.
Обычно разрешается использовать только адрес.
Указанное семейство адресов не поддерживается. Эта ошибка возвращается, если указано семейство IPv6-адресов, а стек протокола IPv6 не установлен на локальном компьютере. Эта ошибка возвращается, если указано семейство IPv4-адресов, а стек протокола IPv4 не установлен на локальном компьютере.
Выбранный IP-адрес является недопустимым в этом контексте.
На незаблокированном сокете Socket уже выполняется операция.
Удаленный узел активно отказывает в подключении.
Подключение сброшено удаленным компьютером.
В операции на сокете Socket пропущен обязательный адрес.
Выполняется правильная последовательность отключения.
Поставщиком основного сокета обнаружен недопустимый указатель адреса.
Ошибка при выполнении операции, вызванная отключением удаленного узла.
Такой узел не существует. Данное имя не является ни официальным именем узла, ни псевдонимом.
Отсутствует сетевой маршрут к указанному узлу.
Выполняется блокирующая операция.
Вызов к заблокированному сокету Socketбыл отменен.
Предоставлен недопустимый аргумент для члена объекта Socket.
Приложение инициировало перекрывающуюся операцию, которая не может быть закончена немедленно.
Объект Socket уже подключен.
У датаграммы слишком большая длина.
Приложение пытается задать значение KeepAlive для подключения, которое уже отключено.
Не существует маршрута к удаленному узлу.
Отсутствует свободное буферное пространство для операции объекта Socket.
Требуемое имя или IP-адрес не найдены на сервере имен.
Неустранимая ошибка, или не удается найти запрошенную базу данных.
Приложение пытается отправить или получить данные, а объект Socket не подключен.
Основной поставщик сокета не инициализирован.
Предпринята попытка выполнить операцию объекта Socket не на сокете.
Перекрывающаяся операция была прервана из-за закрытия объекта Socket.
Семейство адресов не поддерживается семейством протоколов.
Слишком много процессов используется основным поставщиком сокета.
Семейство протоколов не реализовано или не настроено.
Протокол не реализован или не настроен.
Для объекта Socket был использован неизвестный, недопустимый или неподдерживаемый параметр или уровень.
Неверный тип протокола для данного объекта Socket.
Запрос на отправку или получение данных отклонен, так как объект Socket уже закрыт.
Произошла неопознанная ошибка объекта Socket.
Указанный тип сокета не поддерживается в данном семействе адресов.
Операция Socket выполнена успешно.
Подсистема сети недоступна.
Истекло время ожидания попытки подключения, или произошел сбой при отклике подключенного узла.
Слишком много открытых сокетов в основном поставщике сокета.
Не удалось разрешить имя узла. Повторите попытку позже.
Указанный класс не найден.
Версия основного поставщика сокета выходит за пределы допустимого диапазона.
Операция на незаблокированном сокете не может быть закончена немедленно.
Комментарии
Большинство этих ошибок возвращаются базовым поставщиком сокета.
Источник
windows операционные системы ос программы
Adblock
detector
Hi, so I’m learning socket programming in Windows XP. I’m trying to set up a simple server/client interaction, but I can’t seem to get it working. Whenever I run the client, I get a «Socket connect error 10049» message printed to the console (meaning WSAGetLastError() is returning the error number 10049). Error 10049 translates to:
Code:
WSAEADDRNOTAVAIL 10049 0x2741 The requested address is not valid in its context.NOTE: The key part of the code that’s causing the trouble is at the bottom of the code if you don’t want to read all of that.
Here’s the code of the client:
Code:
#include <iostream> #include <winsock2.h> #include <ws2tcpip.h> #include <cstring> #include <Mstcpip.h> using std::cout; using std::cin; using std::endl; WSADATA wsaData; int main(int argc, char * argv[]) { int wsaReturnVal = WSAStartup(MAKEWORD(1, 1), &wsaData); if (wsaReturnVal) { cout << "Error number: " << wsaReturnVal << endl; exit(1); } char * fpoint = strrchr(argv[0], '\'); if (argc != 2) { printf("Usage: <%s> <"string"|ping>", fpoint+1); exit(1); } struct sockaddr_in serv; SOCKET sockfd; memset(serv.sin_zero, '', sizeof(serv.sin_zero)); serv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); serv.sin_family = AF_INET; serv.sin_port = htons(3490); sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == SOCKET_ERROR) { printf("Socket create error %d", WSAGetLastError()); exit(1); } if (connect(sockfd, (struct sockaddr *)&serv, sizeof(sockaddr_in)) == SOCKET_ERROR) { printf("Socket connect error %d", WSAGetLastError()); exit(1); } printf("Connected to server...n"); closesocket(sockfd); if (WSACleanup()) { cout << "Cleanup Error." << endl; exit(1); } }And here is the code of the server:
Code:
#include <iostream> #include <winsock2.h> #include <ws2tcpip.h> #include <cstring> #include <Mstcpip.h> #define MYPORT 3490 #define BACKLOG 10 using std::cout; using std::cin; using std::endl; WSADATA wsaData; int main(int argc, char * argv[]) { int wsaReturnVal = WSAStartup(MAKEWORD(1, 1), &wsaData); if (wsaReturnVal) { cout << "Error number: " << wsaReturnVal << endl; exit(1); } struct sockaddr_in serv, their_addr; SOCKET sockfd, newfd = NULL; memset(&serv, 0, sizeof(serv)); serv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); serv.sin_family = AF_INET; serv.sin_port = htons(MYPORT); if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) { printf("Socket create error %d", WSAGetLastError()); exit(1); } printf("Socket created...n"); if (bind(sockfd, (sockaddr *)&serv, sizeof(sockaddr_in)) == SOCKET_ERROR) { printf("Socket bind error %d", WSAGetLastError()); exit(1); } printf("Bound socket to address: %s...n", serv.sin_addr); if (listen(sockfd, BACKLOG) == -1) { printf("Socket listen error %d", WSAGetLastError()); exit(1); } printf("Listening on socket...n"); int addr_size = sizeof(their_addr); if ((newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size)) == INVALID_SOCKET) { printf("Accept error %d", WSAGetLastError()); closesocket(newfd); exit(1); } closesocket(sockfd); closesocket(newfd); if (WSACleanup()) { printf("Cleanup Error %d", WSAGetLastError()); exit(1); } }NOTE: The server works perfectly fine (other than the address it prints, instead of printing the address it prints «(null)», but I ran a netstat to ensure the socket was working correctly, and it was infact in listening state on port 3490. However I cannot get the client to connect to it… Ok thanks!
EDIT: The following code was taken out of the Client program, but this is where the error lies. Somewhere in here… Because the error is printed at that point, so anything before or up to it is the troublesome code:
Code:
struct sockaddr_in serv; SOCKET sockfd; memset(serv.sin_zero, '', sizeof(serv.sin_zero)); serv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); serv.sin_family = AF_INET; serv.sin_port = htons(3490); sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == SOCKET_ERROR) { printf("Socket create error %d", WSAGetLastError()); exit(1); } if (connect(sockfd, (struct sockaddr *)&serv, sizeof(sockaddr_in)) == SOCKET_ERROR) { printf("Socket connect error %d", WSAGetLastError()); exit(1); }
I’m trying to start an instance of Apache 2.2 server with a fairly-close-to-standard configuration file. I made one small change because I want Apache to serve a single XML file separately from everything else it does, purely for testing on my local machine. The change is that I inserted this into httpd.conf
:
# Based on http://httpd.apache.org/docs/2.2/vhosts/examples.html
Listen 10.11.12.13:85
NameVirtualHost 10.11.12.13:85
<VirtualHost 10.11.12.13:85>
DocumentRoot "C:foobar"
ServerName www.MyCompanyMyProjectFooBarTestURL.com
</VirtualHost>
Attempting to start Apache resulted in this:
(OS 10049)The requested address is not valid in its context. : make_sock: could not bind to address 10.11.12.13:85
no listening sockets available, shutting down
Unable to open logs
No instances of Apache are running. Nothing is using port 85 (or 80 or 8080). There’s nothing special about 10.11.12.13:85
; I just figured that was an IP that wouldn’t interfere with anything.
What does this error mean, and how can I resolve it?
asked Sep 21, 2011 at 19:47
There could be reason the IP address you are pointing is generic one.
For example:-10.1.1.233:443
And you get error >>> (OS 10049)The requested address is not valid in its context. : make_sock: could not bind to address 10.1.1.233:443
comment the line in httpd-ssl.conf
and start the Apache
answered May 8, 2012 at 19:31
in CMD , type: ipconfig
, and see your local IP address. then set this one instead of unknown 10.11.12.13:85
answered Jan 16, 2016 at 14:49
T.ToduaT.Todua
2041 gold badge4 silver badges14 bronze badges
Since nobody has yet explained what is going on:
Apache cannot bind to the local IP address you gave, because the computer is not configured with that IP address.
There are a couple of ways to solve this:
-
You can
Listen
to an IP address that the computer actually has. But keep in mind that specifying an IP address restricts incoming connections, and only other hosts which can reach that address will be able to access the server, and only via that address. For a production web server on the Internet, this is almost always not what you want, so… -
Don’t specify an IP address in the
Listen
directive. Apache will then listen to all interfaces for incoming connections. If it doesn’t matter where the connections come from, such as a publicly accessible web server or one which is properly firewalled, then this is the simplest solution.
answered Jan 16, 2016 at 16:27
Michael HamptonMichael Hampton
240k42 gold badges488 silver badges954 bronze badges
In order to find a socket to bind to you can point to the local machine address. That seems to change when you turn the computer off and on. To find the local address in use, go into control panel, network and sharing center, click on the wireless connection, then on the «details» button, and the IPv4 address should be the local machine address. You can add this address and a good socket like 8088 to httpd.conf as a «Listen» parameter — e.g. Listen 127.0.0.1:8088 (that is a default localhost but your IP will be different) — you can list more than one of these addresses and it will bind to one that is free. This works in windows. Then add the same IP address to the hosts file.
answered Nov 5, 2014 at 23:18
1