Broadcast[UDP] sendto Error on Mac (Code works in Win fine!) - macos

i have a Problem with a Broadcast on MAC using c++ 11
The Code works fine in Windows but on Mac i get a -1 back from my sendto function, maybe u see my error.
#ifdef _WIN32
SOCKET s;
#endif
int recSocket = socket(AF_INET, SOCK_DGRAM, 0);
int askSinlen = sizeof(struct sockaddr_in);
ssize_t askBuflen = MAXBUF;
int recCheckCall;
#ifdef _WIN32
int clientLength;
#elif __APPLE__
socklen_t clientLength;
#endif
int message;
char buf[512];
char askStatus;
char status;
char askBuffer[MAXBUF];
struct sockaddr_in sock_in, server_adress, client_adress, client_adress2;
char askYes = 1;
DEBUG_LOG(35, "Im Boradcast");
#ifdef _WIN32
WSADATA w;
if (int result = WSAStartup(MAKEWORD(2, 2), &w) != 0) // Zugriff auf Winsock Libary
{
DEBUG_LOG(300, "WSA Startup failed");
return -1;
}
#endif
recSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (recSocket == -1)
{
DEBUG_LOG(301, "Receive Socket Error");
#ifdef _WIN32
closesocket(recSocket);
#elif __APPLE__
close(recSocket);
#endif
return -2;
}
sock_in.sin_addr.s_addr = htonl(INADDR_ANY);
sock_in.sin_port = htons(4028);
sock_in.sin_family = PF_INET;
client_adress.sin_family = PF_INET;
client_adress.sin_port = htons(4029);
client_adress.sin_addr.s_addr = htonl(-1);
status = bind(recSocket, (struct sockaddr *)&sock_in, askSinlen);
if (status == -1)
{
DEBUG_LOG(302, "Fehler beim binden des Sockets");
#ifdef _WIN32
closesocket(recSocket);
#elif __APPLE__
close(recSocket);
#endif
return -3;
}
status = setsockopt(recSocket, SOL_SOCKET, SO_BROADCAST, &askYes, sizeof(askYes));
sprintf(askBuffer, "Ciao");
askBuflen = strlen(askBuffer);
status = sendto(recSocket, askBuffer, askBuflen, 0, (struct sockaddr *)&client_adress, sizeof(client_adress));
if (status < 0)
{
DEBUG_LOG(status, "Fehler ist: ");
DEBUG_LOG(303, "Fehler beim senden des Broadcastes");
#ifdef _WIN32
closesocket(recSocket);
#elif __APPLE__
close(recSocket);
#endif
return -4;
}
It would be great if u could help me, i think its just a small bug wich i didnt see...
Have a nice day
Kindly Regards

Related

Mac C++ Broadcast -> more then one network-interface

I have a broadcast program on my mac, everything is working fine, but if i have more then one network interface, he didn't recieve anything.
So what i now want to do is:
Check which network interfaces are activ on the mac
send to every activ interface a broadcast ( so i have to select which interface i want to use)
recieve the answer (if there is one :) )
Interesting:
the broadcast client is on my WLAN (with a router beetween the devices) and a normal internet connection is on my LAN. If i deactivate the LAN in the system configs, he also didn't find my other device, but if i pull the cable he found the other device... So maybe i didn't have to look which interface is activ and have a look to which interface is connected.
Do u have some tipps or good google keywords for me to do that?
Long time ago, but if someone find my post, here is my solution:
#include <stdint.h>
static uint32 Inet_AtoN(const char * buf)
{
// net_server inexplicably doesn't have this function; so I'll just fake it
uint32 ret = 0;
int shift = 24; // fill out the MSB first
bool startQuad = true;
while ((shift >= 0) && (*buf))
{
if (startQuad)
{
unsigned char quad = (unsigned char)atoi(buf);
ret |= (((uint32)quad) << shift);
shift -= 8;
}
startQuad = (*buf == '.');
buf++;
}
return ret;
}
int Broadcast::BroadcastToAllInterfaces()
{
DEBUG_LOG(1,"Start Broadcast To All Interfaces", "DEv1");
globalDatabase->SetInBroadcast();
moreThenOne = 0;
#if defined(USE_GETIFADDRS)
struct ifaddrs * ifap;
if (getifaddrs(&ifap) == 0)
{
struct ifaddrs * p = ifap;
while (p)
{
uint32 ifaAddr = SockAddrToUint32(p->ifa_addr);
uint32 maskAddr = SockAddrToUint32(p->ifa_netmask);
uint32 dstAddr = SockAddrToUint32(p->ifa_dstaddr);
if (ifaAddr > 0)
{
char ifaAddrStr[32]; Inet_NtoA(ifaAddr, ifaAddrStr);
char maskAddrStr[32]; Inet_NtoA(maskAddr, maskAddrStr);
char dstAddrStr[32]; Inet_NtoA(dstAddr, dstAddrStr);
std::stringstream addr, descss;
std::string addrs, descs;
addr << dstAddrStr;
descss << p->ifa_name;
descss >> descs;
addr >> addrs;
DoABroadcast(dstAddr);
}
p = p->ifa_next;
}
freeifaddrs(ifap);
}
#elif defined(WIN32)
// Windows XP style implementation
// Adapted from example code at http://msdn2.microsoft.com/en-us/library/aa365917.aspx
// Now get Windows' IPv4 addresses table. Once again, we gotta call GetIpAddrTable()
// multiple times in order to deal with potential race conditions properly.
MIB_IPADDRTABLE * ipTable = NULL;
{
ULONG bufLen = 0;
for (int i = 0; i<5; i++)
{
DWORD ipRet = GetIpAddrTable(ipTable, &bufLen, false);
if (ipRet == ERROR_INSUFFICIENT_BUFFER)
{
free(ipTable); // in case we had previously allocated it STILL_RUN
ipTable = (MIB_IPADDRTABLE *)malloc(bufLen);
}
else if (ipRet == NO_ERROR) break;
else
{
free(ipTable);
ipTable = NULL;
break;
}
}
}
if (ipTable)
{
IP_ADAPTER_INFO * pAdapterInfo = NULL;
{
ULONG bufLen = 0;
for (int i = 0; i<5; i++)
{
DWORD apRet = GetAdaptersInfo(pAdapterInfo, &bufLen);
if (apRet == ERROR_BUFFER_OVERFLOW)
{
free(pAdapterInfo); // in case we had previously allocated it
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(bufLen);
}
else if (apRet == ERROR_SUCCESS) break;
else
{
free(pAdapterInfo);
pAdapterInfo = NULL;
break;
}
}
}
for (DWORD i = 0; i<ipTable->dwNumEntries; i++)
{
const MIB_IPADDRROW & row = ipTable->table[i];
// Now lookup the appropriate adaptor-name in the pAdaptorInfos, if we can find it
const char * name = NULL;
const char * desc = NULL;
if (pAdapterInfo)
{
IP_ADAPTER_INFO * next = pAdapterInfo;
while ((next) && (name == NULL))
{
IP_ADDR_STRING * ipAddr = &next->IpAddressList;
while (ipAddr)
{
if (Inet_AtoN(ipAddr->IpAddress.String) == ntohl(row.dwAddr))
{
name = next->AdapterName;
desc = next->Description;
break;
}
ipAddr = ipAddr->Next;
}
next = next->Next;
}
}
char buf[128];
int setUnnamed = 0;
if (name == NULL)
{
sprintf(buf, "unnamed");
name = buf;
setUnnamed = 1;
}
uint32 ipAddr = ntohl(row.dwAddr);
uint32 netmask = ntohl(row.dwMask);
uint32 baddr = ipAddr & netmask;
if (row.dwBCastAddr) baddr |= ~netmask;
char ifaAddrStr[32]; Inet_NtoA(ipAddr, ifaAddrStr);
char maskAddrStr[32]; Inet_NtoA(netmask, maskAddrStr);
char dstAddrStr[32]; Inet_NtoA(baddr, dstAddrStr);
std::stringstream addr, descss;
std::string addrs, descs;
if (setUnnamed == 0)
{
addr << dstAddrStr;
descss << desc;
descss >> descs;
addr >> addrs;
DoABroadcast(baddr);
}
}
free(pAdapterInfo);
free(ipTable);
}
#else
// Dunno what we're running on here!
# error "Don't know how to implement PrintNetworkInterfaceInfos() on this OS!"
#endif
globalDatabase->SetLeaveBroadcast();
return 1;
}
int Broadcast::DoABroadcast(uint32 broadAddr)
{
int askSinlen = sizeof(struct sockaddr_in);
int askBuflen = MAXBUF;
int message;
char buf[512];
int status;
char askBuffer[MAXBUF];
struct sockaddr_in sock_in, client_adress, client_adress2;
#ifdef __APPLE__
socklen_t clientLength;
int askYes = 1;
#else
char askYes = 1;
int clientLength;
WSADATA w;
int result = WSAStartup(MAKEWORD(2, 2), &w);
#endif
int recSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (recSocket <0)
{
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return 10;
}
sock_in.sin_addr.s_addr = htonl(INADDR_ANY);
sock_in.sin_port = htons(4028);
sock_in.sin_family = PF_INET;
client_adress.sin_family = PF_INET;
client_adress.sin_port = htons(4029);
client_adress.sin_addr.s_addr = htonl(broadAddr);
askSinlen = sizeof(sock_in);
client_adress2.sin_family = AF_INET;
client_adress2.sin_port = htons(4028);
client_adress2.sin_addr.s_addr = htonl(0xc0a8b2ff);
status = setsockopt(recSocket, SOL_SOCKET, SO_BROADCAST, &askYes, sizeof(askYes));
if (status < 0)
{
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return 10;
}
status = bind(recSocket, (struct sockaddr *)&sock_in, askSinlen);
if (status < 0)
{
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return 10;
}
askBuflen = sprintf(askBuffer, "Ciao Mac ist hier");
status = sendto(recSocket, askBuffer, askBuflen, 0, (struct sockaddr *)&client_adress, sizeof(client_adress));
fd_set fds;
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(recSocket, &fds);
int ret;
if ((ret = select(recSocket +1, &fds, NULL, NULL, &tv)) > 0)
{
int e = 0;
while ((ret = select(recSocket + 1, &fds, NULL, NULL, &tv)) > 0)
{
clientLength = sizeof(client_adress2);
message = recvfrom(recSocket, buf, sizeof(buf), 0, (struct sockaddr*) &client_adress2, &clientLength);
if (message == -1)
{
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return -5;
}
else
{
std::string hereisyourbroadcast(buf);
}
}
}
else
{
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return -6;
}
#ifdef __APPLE__
close(recSocket);
#else
closesocket(recSocket);
#endif
inBroadcast = false;
return 1;
}

error C1083 visual studio 2013 for winsock server

i'm new at this website.
i searched a lot for a solution but i didn't find nothing about it.
i programmed a server and a client on another project and it was working but i wanted to re-program it to have a better results.
but i dunno why i have some errors: error C1083: impossible to open: 'Debug\chatserver.pch': No such file or directory c:\users\x\documents\visual studio 2013\projects\chatserver\chatserver\chatserver.cpp
before this error, i had another error on 'itoa' function: C4996 'itoa' POSIX ...
(itoa function was working on my 1st server project)
also i had error on LNK 2011 to .obj
this is the code:
#include "stdafx.h"
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <cstdlib>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
using namespace std;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket;
SOCKET* Connessioni;
int nConn = 0;
struct Buffer
{
int ID;
char nickname[20];
char messaggio[1024];
};
int ServerThread(int ID)
{
Buffer buff;
char* Recv = new char[1024];
char* Pnick = new char[20];
char* Send = new char[1024];
Recv = NULL;
Pnick = NULL;
Send = NULL;
for (;;){
if (recv(Connessioni[ID], Recv, 1024, NULL) && recv(Connessioni[ID], Pnick, 20, NULL))
buff.ID = ID;
memcpy(buff.nickname, Pnick, 1024);
memcpy(buff.messaggio, Recv, 1024);
memcpy(Send, &buff, sizeof(Buffer));
for (int i = 0; i != nConn; i++)
{
if (Connessioni[i] == Connessioni[ID])
{
}
else{
send(Connessioni[i], Send, sizeof(Buffer), NULL);
}
}
delete Recv;
delete Send;
delete Pnick;
delete &Recv;
delete &Send;
delete &Pnick;
}
return 0;
}
int InitWinSock()
{
int RetVal = 0;
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 2);
RetVal = WSAStartup(DllVersion, &wsaData);
if (RetVal != 0)
MessageBoxA(NULL, "WSA error, please retry", "Error", MB_OK | MB_ICONERROR);
return RetVal;
}
int main()
{
struct addrinfo *result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
int controllo_struct = getaddrinfo(NULL,DEFAULT_PORT, &hints, &result);
if (controllo_struct != 0)
{
MessageBoxA(NULL, "getinfo failes \n", "Error", MB_OK | MB_ICONERROR);
WSACleanup();
return 1;
}
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
MessageBoxA(NULL, "Error at Socket, please retry \n", "Error", MB_OK | MB_ICONERROR);
freeaddrinfo(result);
WSACleanup();
}
int controllo_bind = bind(ListenSocket,result->ai_addr,(int)result->ai_addrlen);
if (controllo_bind == SOCKET_ERROR)
{
MessageBoxA(NULL, "bind ha fallito \n", "Error", MB_OK | MB_ICONERROR);
cout << WSAGetLastError() << endl;
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR){
MessageBoxA(NULL, "Listen ha fallito \n", "Error", MB_OK | MB_ICONERROR);
cout << WSAGetLastError() << endl;
closesocket(ListenSocket);
return 1;
}
ClientSocket = INVALID_SOCKET;
int addrlen = sizeof(hints);
for (;;){
if (ClientSocket = accept(ListenSocket, (SOCKADDR*)&hints, &addrlen))
Connessioni = (SOCKET*)calloc(SOMAXCONN, sizeof(hints));
cout << "connessione accettata " << endl;
Connessioni[nConn] = ClientSocket;
char* nickname = new char[20];
ZeroMemory(nickname, sizeof(nickname));
//itoa(nConn,nickname,10);
//nickname = (char*)nConn;
send(Connessioni[nConn], nickname, sizeof(nickname), NULL);
++nConn;
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ServerThread, (LPVOID)(nConn - 1), NULL, NULL);
delete nickname;
}
return 0;
}
RESOLVED:
DISABLED: "PRECOMPILED HEADER"
on c/c++ -> all options ->> "precompiled header (selected: NO)

PGM winsock2 failure to create socket

I just found out about PGM (Pragmatic General Multicast) in windows sockets. I read up on msdn how to configure a send and receive socket but it's not working.
This is the code so far:
#pragma comment(lib,"Ws2_32.lib")
#include <stdio.h>
#include <iostream>
#include <ws2tcpip.h>
#include <Winsock2.h>
#include <wsrm.h>
int main( int argc, const char* argv[] )
{
DWORD dwRet = NO_ERROR;
WSADATA wsa_data;
if( WSAStartup( MAKEWORD( 2, 0 ), &wsa_data ) != 0 ) {
dwRet = GetLastError();
WSACleanup();
return dwRet;
}
SOCKET s;
SOCKADDR_IN salocal, sasession;
int dwSessionPort;
s = socket( AF_INET, SOCK_RDM, IPPROTO_RM );
if( s == INVALID_SOCKET )
{
dwRet = GetLastError();
WSACleanup();
return dwRet;
}
salocal.sin_family = AF_INET;
salocal.sin_port = htons (0); // Port is ignored here
salocal.sin_addr.s_addr = htonl (INADDR_ANY);
int iRet = bind (s, (SOCKADDR *)&salocal, sizeof(salocal));
if( iRet == SOCKET_ERROR )
{
dwRet = GetLastError();
WSACleanup();
return dwRet;
}
dwSessionPort = 0;
sasession.sin_family = AF_INET;
sasession.sin_port = htons (dwSessionPort);
sasession.sin_addr.s_addr = inet_addr ("234.5.6.7");
connect (s, (SOCKADDR *)&sasession, sizeof(sasession));
return dwRet;
}
I get error code 10044 (Socket type not supported) when i try to create the socket. How do I enable the use of PGM?
I'm currently working on Windows 7 with MSMQ installed.
EDIT
This is the msdn site I read up on.
Found the solution, the MSMQ wasn´t properly installed. In order for it to include all features (Multicast Support) all the subfolders had to be explicitly checked as shown in the picture below.

Why can't people connect to my server app?

I have a server written in C under Windows, but I can only seem to connect to it from machines that are also connected to the router my computer is connected to. Any ideas why? Here's my code:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#pragma comment(lib,"Ws2_32.lib")
#define PORT "1234"
#define BUFLEN 512
DWORD ErrorMessage(char* msg, int error)
{
printf("ErrorMessage: %s\nCodErr: %d\n", msg, error);
return -1;
}
void PrintArray(char* v, unsigned int len)
{
for(unsigned int i = 0 ; i < len ; i++)
printf("%c",v[i]);
printf("\n");
}
DWORD WINAPI ClientHandler(LPVOID lpParam)
{
SOCKET ClientSocket = *((SOCKET*)lpParam);
char recvbuf[BUFLEN];
int iResult,iSendResult;
do
{
iResult = recv(ClientSocket, recvbuf, BUFLEN, 0);
if(iResult > 0)
{
PrintArray(recvbuf,iResult);
iSendResult = send(ClientSocket, recvbuf, iResult, 0);
if(iSendResult == SOCKET_ERROR)
{
closesocket(ClientSocket);
WSACleanup();
return ErrorMessage("send",WSAGetLastError());
}
}
else if(iResult == 0)
printf("Connection closing...\n");
else
{
closesocket(ClientSocket);
WSACleanup();
return ErrorMessage("recv",WSAGetLastError());
}
}
while(iResult > 0);
return 0;
}
int main()
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
if(iResult != 0)
{
printf("WSAStartup failed and with error code: %d\n",iResult);
return ErrorMessage("WSAStartup",GetLastError());
}
struct addrinfo *result = NULL, *ptr = NULL, hints;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL,PORT,&hints,&result);
if(iResult != 0)
{
printf("getaddrinfo failed %d\n",iResult);
WSACleanup();
return -1;
}
SOCKET ListenSocket = INVALID_SOCKET;
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if(ListenSocket == INVALID_SOCKET)
{
freeaddrinfo(result);
WSACleanup();
return ErrorMessage("socket",WSAGetLastError());
}
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if(iResult == SOCKET_ERROR)
{
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("bind", WSAGetLastError());
}
freeaddrinfo(result);
if(listen(ListenSocket,5) == SOCKET_ERROR)
{
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("listen",WSAGetLastError());
}
SOCKET ClientSocket = INVALID_SOCKET;
sockaddr sa;
while(true)
{
ClientSocket = accept(ListenSocket, &sa /*NULL*/, NULL);
if(ClientSocket == INVALID_SOCKET)
{
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("accept",WSAGetLastError());
}
printf("New client arrived...\n");
if(CreateThread(NULL, 0, ClientHandler, &ClientSocket, 0, NULL) == NULL)
ErrorMessage("CreateThread",GetLastError());
}
iResult = shutdown(ClientSocket,SD_BOTH);
if(iResult == SOCKET_ERROR)
{
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("shutsown",WSAGetLastError());
}
closesocket(ListenSocket);
WSACleanup();
return 0;
}
I can't follow your code, but usually I use bind with htons. In your code, it's not obvious how you convert your string "1234" into a numeric value. I wrote a very crude simple Web Server on port 1234 that just serves out a dummy "Hello World" page. All validation has been removed to keep the example short:
#include "stdafx.h"
#include <tchar.h>
#include <windows.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData = {0};
WSAStartup(0x202, &wsaData);
SOCKET serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN sin = {0};
sin.sin_family = PF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.s_addr = INADDR_ANY;
bind(serverSocket, (LPSOCKADDR) &sin, sizeof(sin));
listen(serverSocket, 1);
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
while (clientSocket != INVALID_SOCKET)
{
char request[1024] = {0};
recv(clientSocket, request, 1024, 0);
static char html[] =
"HTTP/1.1 200 OK\n"
"Content-Type: text/html\n"
"\n"
"<HTML><HEAD><TITLE>Hello World!</TITLE></HEAD><BODY>Hello World!</BODY></HTML>\n\n";
send(clientSocket, html, sizeof(html), 0);
closesocket(clientSocket);
clientSocket = accept(serverSocket, NULL, NULL);
}
closesocket(serverSocket);
WSACleanup();
return 0;
}
The problem is not in your program. The problem is in the configuration of your router.
Try to connect to some other TCP/IP service on your computer from outside.

Multicast problem on Windows XP

I'm testing out multicast with the two programs below. The client run well on linux and in wine on two of my machines, but it won't work properly on my windows machine (in Virtualbox).
Strangely, if I start up vlc in windows and open the udp stream, the client program receives the packets - and when I stop vlc, the client goes silent again.
What am I doing wrong?
Here is the the server program:
/*
* server.c - multicast server program.
*/
#include <sys/types.h>
#ifdef WINDOWS
#include <winsock.h>
#include <windows.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <time.h>
#include <string.h>
#include <stdio.h>
#define HELLO_PORT 5004
#define HELLO_GROUP "224.0.0.1"
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd, cnt, numbytes;
struct ip_mreq mreq;
char message[100];
#ifdef WINDOWS
WSADATA wsaData; /* Windows socket DLL structure */
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
fprintf(stderr, "WSAStartup() failed");
return 1;
}
#endif
/* create what looks like an ordinary UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "failed to create socket.\n");
return 1;
}
/* set up destination address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(HELLO_GROUP);
addr.sin_port = htons(HELLO_PORT);
/* now just sendto() our destination! */
cnt = 0;
while (1) {
numbytes = sprintf(message, "%d", cnt);
if (sendto(fd, message, numbytes, 0, (struct sockaddr*)&addr,
sizeof(addr)) < 0) {
fprintf(stderr, "sendto failed.\n");
return 1;
}
#ifdef WINDOWS
Sleep(1000);
#else
sleep(1);
#endif
cnt++;
}
return 0;
}
and here's the client program:
/*
* client.c -- client program for udp multicast data.
*/
#include <sys/types.h>
#ifdef WINDOWS
#include <winsock.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <time.h>
#include <string.h>
#include <stdio.h>
#define HELLO_GROUP "224.0.0.1"
#define HELLO_PORT 5004
#define MSGBUFSIZE 256
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int fd, nbytes,addrlen;
struct ip_mreq mreq;
char msgbuf[MSGBUFSIZE];
u_int yes = 1;
#ifdef WINDOWS
WSADATA wsaData; /* Windows socket DLL structure */
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
fprintf(stderr, "WSAStartup() failed");
return 1;
}
#endif
/* create what looks like an ordinary UDP socket */
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
fprintf(stderr, "failed to create socket.\n");
return 1;
}
/* allow multiple sockets to use the same PORT number */
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes)) != 0) {
fprintf(stderr, "failed to reuse port number.\n");
return 1;
}
/* set up destination address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(HELLO_PORT);
/* bind to receive address */
if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
fprintf(stderr, "failed to bind socket.\n");
return 1;
}
/* use setsockopt() to request that the kernel join a multicast group */
mreq.imr_multiaddr.s_addr = inet_addr(HELLO_GROUP);
mreq.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) != 0) {
fprintf(stderr, "failed to join the multicast group.\n");
return 1;
}
/* now just enter a read-print loop */
while (1) {
addrlen = sizeof(addr);
nbytes = recvfrom(fd, msgbuf, MSGBUFSIZE, 0,
(struct sockaddr*)&addr, &addrlen);
if (nbytes < 0) {
fprintf(stderr, "recfrom failed, %d\n", nbytes);
return 1;
}
msgbuf[nbytes] = '\0';
puts(msgbuf);
}
return 0;
}
Thanks,
Oskar
Ok, so apparently the firewall blocked the packets. Turning it off fixes the issue.

Resources