Udp 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

Содержание

  1. bind() fails with windows socket error 10049
  2. 4 Answers 4
  3. Ошибка Winsock 10049 пытается связать
  4. Решение
  5. Другие решения
  6. Socket UDP from local computer, Error code 10049
  7. 2 Answers 2
  8. Windows socket error code 10049
  9. Socket Error Перечисление
  10. Определение
  11. Комментарии

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.

bcmrv

rXvMA

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

Репутация: нет
Всего: нет

Эксперт
pippippippip

Профиль
Группа: Участник Клуба
Сообщений: 8564
Регистрация: 24.6.2003
Где: Europe::Ukraine:: Kiev

Репутация: 5
Всего: 98

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

Эксперт
pippippippip

Профиль
Группа: Модератор
Сообщений: 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

Репутация: нет
Всего: нет

Брутальный буратина
pippippippip

Профиль
Группа: Участник Клуба
Сообщений: 3497
Регистрация: 31.3.2002
Где: Лес

Репутация: 10
Всего: 115

Эксперт
pippippippip

Профиль
Группа: Модератор
Сообщений: 11363
Регистрация: 13.10.2004
Где: Питер

Репутация: 53
Всего: 484

Профиль
Группа: Участник
Сообщений: 9
Регистрация: 7.6.2004

Репутация: нет
Всего: нет

sceloglauxalbifacies
pippippippip

Профиль
Группа: Экс. модератор
Сообщений: 2929
Регистрация: 16.6.2006

Репутация: 5
Всего: 158

p pm on p email on p www on p im on p icq on p aim on p yim on p msn on p skype on p gtalk on p jabber on p report on p delete on p edit on p quick quote on p quote on p show on p hide on p tofaq on

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

  • Remove From My Forums
  • Question

  • 1. We have a socket which is bound to the local IP address of the machine i.e the IP of the machice on which the application is running.
    The sample code is as pasted below,

    s = socket(PF_INET, SOCK_DGRAM, 0);

    bool reuse = 1;
    struct sockaddr_in srv_addr;
    memset(&srv_addr,0,sizeof(srv_addr));
    srv_addr.sin_family = PF_INET;
    srv_addr.sin_addr.s_addr = inet_addr(ipaddr);

    srv_addr.sin_port = htons(port); // example port is 7000

    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse, sizeof(reuse));

    bind(s, (LPSOCKADDR)&srv_addr, sizeof(srv_addr));

    2. There is another piece of code where we write data; The same socket created above then is used in sendto() like below

    sendto(s, msg, bytesToSend, 0, (SOCKADDR *)&Addr, sizeof(Addr));

    The send to function fails with error code 10049; The same code used to work on WinXP

    below is the way in which the Addr, sturcture is filled

    Note: we have used the loopback address

    memset(&Addr,0,sizeof(Addr));
    Addr.sin_family = AF_INET;
    Addr.sin_addr.s_addr = inet_addr(«127.0.0.1» ); //Will be in Network Byte Order
    Addr.sin_port = htons(port);  //same port as the one mentioned in step 1; example 7000
    memset(&(replicationAddr.sin_zero), », 8); // zero the rest of the struct

    Note: The Firewall is disabled and the port number is not zero

    Has anyone faced this issue and found the reason for it. Also is there any workaround for this?

    Thanks. 

    • Moved by

      Monday, July 30, 2012 6:21 AM
      (From:Visual C++ Language)

У меня проблема с подключением к серверу. При попытке привязать сервер к 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

Понравилась статья? Поделить с друзьями:
  • Ubuntu server 500 internal server error
  • Ubuntu repository gpg error
  • Ubuntu read only file system как исправить
  • Ubuntu phpmyadmin error 1045
  • Ubuntu permission denied как исправить