Amit
Amit

Reputation: 703

Trying to create UDP Server

I'm trying to create a UDP Server ,though without even client connecting to it, it recieves a connection... (It writes in the console - New Connection a lot, so I guess it gets a 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 a SOCKET for listening for
// incoming connection requests.
ListenSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (ListenSocket == INVALID_SOCKET) 
{
    WSACleanup();
    exit(1);
}

// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is 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 is it getting connected without I ran anything? Maybe something else tries to connect to my server?

Thanks!

Upvotes: 0

Views: 484

Answers (1)

user3F31A28
user3F31A28

Reputation: 104

Two things: I don't think the IP address of your server can be 0.0.0.0, but instead 10.0.0.2; and also, UDP doesn't support the concept of 'accept'. There are just packets, and you can either bind a socket to a port, then receive packets from a specific IP (with recvfrom), or you can receive packets from anyone, with recv. The latter will be useful in case of a server. Note that you manually have to keep track of each connected client with a sockaddr_in structure.

Upvotes: 1

Related Questions