Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5702429
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2007-06-09 16:48:23

一般使用的socket编程都是使用的是一些绑定端口和ip的普通的程序,一旦想要编写一些特殊的网络应用程序就会出现一些问题。
就那这个UDP广播数据的车姑娘许来说,需要设置socket的选项,也就是使用setsockopt来设置socket的一些特殊选项。

#include
#include
#include
#include
#include
#include
#include
#include
#include

#define PORT 51654

int main(int argc,char* argv[])
{
        int sockfd;
        struct sockaddr_in their_addr;
        struct in_addr addr;
        struct hostent *he;
        int broadcast = 1;
        int num = 0;


        if(argc != 3)
        {
                fprintf(stderr,"Usage: broadcase hostname message\n");
                exit(1);
        }

        if( inet_aton(argv[1],&addr) == 0)
        {
                he = gethostbyname(argv[1]); //Domain
                addr.s_addr = (*(unsigned int *)*he->h_addr_list[0]);
        }

        if( (sockfd = socket(AF_INET,SOCK_DGRAM,0)) == -1 )
        {
                perror("socket function!\n");
                exit(1);
        }

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

        their_addr.sin_family = AF_INET;
        their_addr.sin_port = htons(PORT);
        their_addr.sin_addr = addr;

        if( (num = sendto( sockfd,argv[2],strlen(argv[2]),0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr) )) == -1)
        {
                perror("sendto function!\n");
                exit(1);
        }

        printf("Send %d bytes to %s\n",num,inet_ntoa(their_addr.sin_addr) );

        close(sockfd);

        return 0;
}
这样的话,向广播地址255.255.255.255发送数据就可以广播数据了。

阅读(5153) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~