网络编程udp包

时间:2010-11-08 13:04:57

标签: c sockets

当我编译它时,我为udp广播编写了一个代码然后错误 inet_addr未在此范围内声明 在此范围内未声明睡眠 在此范围内未声明close 请指导我,我是编程新手

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;
}

1 个答案:

答案 0 :(得分:11)

对于inet_addr,您需要:

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

对于sleepclose,您需要:

#include <unistd.h>