Listen Thread

/* ListenThread.cpp
 * <<<<STUDENT NAME>>>>
 * Period <<<X>>> - Computer 12
 * Final Project
 * ListenThread - Listens for Multicast data on the Computer 12 Chat
 * Channel
 * <<<Today's Date 04-01-20XX>>> - File Implemented
 * Changelog:
 */
#include "MainDefs.h"
#include <windows.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>

extern int ProgramRunning;


DWORD ListenThread(LPVOID Parms){

    
     struct sockaddr_in addr;
     int nbytes;
     unsigned int fd;
     socklen_t addrlen;
     struct ip_mreq mreq;
     char msgbuf[255];
     u_int yes=1;  
     char str[INET_ADDRSTRLEN];
     /*For converting recv'd address to IPv4 Address*/
     struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&addr;
     struct in_addr ipAddr;
     printf("In Listen Thread\n");
     /*Set up the socket*/
     
        /* create what looks like an ordinary UDP socket */
        if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0) {
              perror("socket");
              ProgramRunning=0;

            return(0);

        }


       /* allow multiple sockets to use the same PORT number */
        if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0) {
                ProgramRunning=0;
                perror("Reusing ADDR failed");

            return(0);

        }

         /* set up destination address */
        memset(&addr,0,sizeof(addr));
        addr.sin_family=AF_INET;
        addr.sin_addr.s_addr=htonl(INADDR_ANY); /* N.B.: differs from sender */
        addr.sin_port=htons(PORT);
     
        /* bind to receive address */
        if (bind(fd,(struct sockaddr *) &addr,sizeof(addr)) < 0) {
              perror("bind");

            return(0);

        }
     
        /* use setsockopt() to request that the kernel join a multicast group */
        mreq.imr_multiaddr.s_addr=inet_addr(MCAST_CHANNEL);
        mreq.imr_interface.s_addr=htonl(INADDR_ANY);
        if (setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)) < 0) {
             perror("setsockopt");

            return(0);

        }

     
    
    while (ProgramRunning){
        memset(msgbuf,0,255);
        addrlen=sizeof(sockaddr);
        if ((nbytes=recvfrom(fd,msgbuf,BUFFER_SIZE,0,(struct sockaddr *) &addr,&addrlen)) < 0) {
            perror("recvfrom");

            return(0);

        }
        
        //Get the clients address
        ipAddr = pV4Addr->sin_addr;
        inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );
        
        printf("%s:%s\n",str,msgbuf);
    }
}