开发者

Network programming udp packet

I write a code for udp broadcast when i compiled it then error are inet_addr was not declared in this scope sleep was not declared in this scope close was not declared in this scope please guide me i am new to programming

sender.c:

#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>


#define PORT 2080
// #define SRC_ADDR "172.16.1.120"
#define DEST_ADDR "255.255.255.255"

int main(int argc, char *argv[])
{
        int sockfd;
        int broadcast=1;
        struct sockaddr_in sendaddr;
        struct sockaddr_in recvaddr;
        int numbytes;

        if((sockfd = socket(PF_INET,SOCK_DGRAM,0)) == -1)
        {
                perror("sockfd");
                exit(1);
        }

       if((setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,
                                &broadcast,sizeof broadcast)) == -1)
        {
                perror("setsockopt - SO_SOCKET ");
                exit(1);
        }

        sendaddr.sin_family = AF_INET;
        sendaddr.sin_port = htons(PORT);
        sendaddr.sin_addr.s_addr = INADDR_ANY;
        memset(sendaddr.sin_zero,'\0',sizeof sendaddr.sin_zero);

        if(bind(sockfd, (struct sockaddr*) &sendaddr, sizeof sendaddr) == -1)
        {
                perror("bind");
    开发者_如何转开发            exit(1);
        }

        recvaddr.sin_family = AF_INET;
        recvaddr.sin_port = htons(PORT);
        recvaddr.sin_addr.s_addr = inet_addr(DEST_ADDR);
        memset(recvaddr.sin_zero,'\0',sizeof recvaddr.sin_zero);

        while((numbytes = sendto(sockfd, "abcd", 4 , 0,
        (struct sockaddr *)&recvaddr, sizeof recvaddr)) != -1)
   {
                printf("Sent a packet");
                sleep(1000);
   }
        perror("sendto");
        exit(1);


        close(sockfd);

        return 0;
}


For inet_addr you need:

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

For sleep and close you need:

#include <unistd.h>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜