Problem with UDP
I have made a simple programm that implement a server. This server must listen in a port and return a request connection. It's simple!
But I need that also broadcast request are captured. For this reason i discovery that i can't use SOCK_STREAM and IPPROTO_TCP and so I try to use SOCK_DGRAM with IPPROTO_UDP setting with the SO_BRODCAST option.
This is the code:
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "21021"
int __cdecl main(void)
{
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET,
ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
hints;
char recvbuf[DEFAULT_BUFLEN];
int iResult,
recvbuflen = DEFAULT_BUFLEN,
sinLenght = sizeof(struct sockaddr_in);
struct sockaddr_in sin;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
char *re;
re = new char;
sprintf(re,"%d",1);
iResult = setsockopt(ListenSocket, SOL_SOCKET, SO_BROADCAST, re, sizeof(int));
if (iResult == SOCKET_ERROR){
printf("set socket's option failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
printf("Press ENTER to contiune...");
getchar();
return 1;
}
iResult =recvfrom(ListenSocket,recvbuf,recvbuflen,0,(LPSOCKADDR)&sin,&sinLenght);
if (iResult == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// shutdown the connection since we're done
iResult = shutdown(ListenSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
printf("Press ENTER to contiune...");
getchar();
return 0;
}
The program stop to recvfrom and don't step ahead also if a request if sent on the net.
Somebody can help me?
Thank's.
P.S. Sorry for my english!

