Reputation: 125
I am trying to send a string over a udp socket in c++. Whenever i run this code, it always prints connection found infinitely. What am i doing wrong here? I'm not sure what it is seeing as a connection being made to it while listening or if something in my listening code is wrong? Any help would be appreciated :)
void main()
{
long sucessful;
WSAData WinSockData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2, 1);
sucessful = WSAStartup(DLLVERSION, &WinSockData);
SOCKADDR_IN ADDRESS;
int cacheSize = sizeof(ADDRESS);
SOCKET sock_LISTEN;
SOCKET sock_CONNECTION;
sock_CONNECTION = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
ADDRESS.sin_addr.s_addr = inet_addr("127.0.0.1");
ADDRESS.sin_family = AF_INET;
ADDRESS.sin_port = htons(444);
sock_LISTEN = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bind(sock_LISTEN, (SOCKADDR*)&ADDRESS, sizeof(ADDRESS));
listen(sock_LISTEN, SOMAXCONN);
for (;;) {
if (sock_CONNECTION = accept(sock_LISTEN,NULL, NULL)) {
cout << "connection was found \n";
sucessful = send(sock_CONNECTION, "I SEE YOU JAVA!", 100, NULL);
}
}
}
Upvotes: 0
Views: 36
Reputation: 596216
UDP is connection-less, you can't call listen()
or accept()
on a UDP socket. They will both fail and report WSAEOPNOTSUPP
from WSAGetLastError()
.
You are ignoring errors from listen()
.
You are not testing the return value of accept()
correctly. When accept()
fails, it returns INVALID_SOCKET
, which is defined as (SOCKET)(~0)
(aka -1
casted to a SOCKET
). Any non-zero value will evaluate as true in a boolean expression, such as an if
statement.
There is no way to detect whether a UDP listener is running before you send packets to it. All you can do is unconditionally send packets and hope that responses are sent back.
Upvotes: 1