c++ - Trying to create UDP Server -
i'm trying create udp server ,though without client connecting it, recieves connection... (it writes in console - new connection
lot, guess gets new connection suddenly...)
#include <iostream> #include <string> #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #pragma comment(lib, "ws2_32.lib") socket serveron() { socket listensocket; wsadata wsadata; int iresult = wsastartup(makeword(2, 2), &wsadata); if (iresult != no_error) { exit(0); } // create socket listening // incoming connection requests. listensocket = socket(af_inet, sock_dgram, ipproto_udp); if (listensocket == invalid_socket) { wsacleanup(); exit(1); } // sockaddr_in structure specifies address family, // ip address, , port socket being bound. sockaddr_in service; service.sin_family = af_inet; service.sin_addr.s_addr = inet_addr("0.0.0.0"); service.sin_port = htons(2583); if (bind(listensocket,(sockaddr *) & service, sizeof (service)) == socket_error) { closesocket(listensocket); wsacleanup(); exit(2); } return listensocket; } int main() { socket listensocket = serveron(); socket clientsocket; sockaddr_in service; service.sin_family = af_inet; service.sin_addr.s_addr = inet_addr("10.0.0.2"); service.sin_port = htons(2583); while(true) { if (clientsocket = accept(listensocket, (sockaddr*)&service, null)) { std::cout << "new connection!" << std::endl; } } }
why getting connected without ran anything? maybe else tries connect server?
thanks!
two things: don't think ip address of server can 0.0.0.0, instead 10.0.0.2; , also, udp doesn't support concept of 'accept'. there packets, , can either bind socket port, receive packets specific ip (with recvfrom), or can receive packets anyone, recv. latter useful in case of server. note manually have keep track of each connected client sockaddr_in structure.
Comments
Post a Comment