Thursday 21 March 2013

Broadcast c code


Server side:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main()
{
            int soc,flag=1;
            struct sockaddr_in addr;
            soc=socket(PF_INET,SOCK_DGRAM,0);
            addr.sin_family=AF_INET;
            addr.sin_port=htons(10000);
            addr.sin_addr.s_addr = INADDR_BROADCAST;
            setsockopt(soc, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag));
            sendto(soc, "Hello", 6, 0, (struct sockaddr*)&addr, sizeof(addr));
}


 Client Side

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main()
{
            int soc,len;
            char line[10];
            struct sockaddr_in addr,addr1;
            soc=socket(PF_INET,SOCK_DGRAM,0);
            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = INADDR_ANY;
            addr.sin_port=htons(10000);
            bind(soc, (struct sockaddr*)&addr, sizeof(addr));
            len=sizeof(addr1);
            while(1)
            {
                        recvfrom(soc,line,10,0,(struct sockaddr *)&addr1,&len);
                        printf("%s\n",line);
            }
}

No comments:

Post a Comment

Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.