Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.1 kB
3
Indexable
Never
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>

#define err(x,val) if(x<0){printf("%s error!\n",val);exit(0);}

int main(){
    struct sockaddr_in serv;
    struct sockaddr_in broadcastServ;
    int val = 1;
    char buf[100];
    int sock;

    sock = socket(AF_INET,SOCK_DGRAM,0);
    err(sock,"socket");


    err(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&val,sizeof(val)),"socket set");
    
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr =INADDR_ANY;
    serv.sin_port = htons(17000);

    err(bind(sock,(struct sockaddr*)&serv,sizeof(serv)),"bind");

    broadcastServ.sin_family = AF_INET;
    broadcastServ.sin_port = htons(20000);
    broadcastServ.sin_addr.s_addr = inet_addr("127.255.255.255"); //172.16.63.255 -> to broadcast across network to other PCs


    while(1){
        memset(buf,0,100);
        
        fgets(buf,sizeof(buf),stdin);
        sendto(sock,buf,strlen(buf),0,(struct sockaddr*)&broadcastServ,sizeof(broadcastServ));
    }


    return 0;
}