Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1092352
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类: LINUX

2011-05-30 10:44:18

#include
#include
#include
#include
#include
#include
#include
 
struct in_addr localInterface;
struct sockaddr_in groupSock;
int sd;
int main (int argc, char **argv)
{
 char databuf[1024] = "1111111111111111111111111111";
 int datalen = strlen(databuf);
 if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
 {
    perror("Opening datagram socket error");
    exit(1);
 }
 
 /* Initialize the group sockaddr structure with a */
 /* group address of 226.1.1.1 and port 4321. */
 memset((char *) &groupSock, 0, sizeof(groupSock));
 groupSock.sin_family = AF_INET;
 groupSock.sin_addr.s_addr = inet_addr("226.1.1.1");
 groupSock.sin_port = htons(4321);
 /* Send a message to the multicast group specified by the*/
 /* groupSock sockaddr structure. */
 if(sendto(sd, databuf, datalen, 0, (struct sockaddr*)&groupSock, sizeof(groupSock)) < 0)
 {
  perror("Sending datagram message error");
 }
 else
    printf("Sending datagram message...OK\n");
 return 0;
}
================================================================
#include
#include
#include
#include
#include
#include
#include
struct sockaddr_in localSock;
struct ip_mreq group;
int sd;
int datalen;
char databuf[1024];
int main(int argc, char *argv[])
{
 /* Create a datagram socket on which to receive. */
 if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
 {
  perror("Opening datagram socket error");
  exit(1);
 }
 /* Bind to the proper port number with the IP address */
 /* specified as INADDR_ANY. */
 memset((char *)&localSock, '\0', sizeof(localSock));
 localSock.sin_family = AF_INET;
 localSock.sin_port = htons(4321);
 localSock.sin_addr.s_addr = htonl(INADDR_ANY);
 if(bind(sd, (struct sockaddr*)&localSock, sizeof(localSock)))
 {
  perror("Binding datagram socket error");
  close(sd);
  exit(1);
 }
 /* Join the multicast group 226.1.1.1 on the local 203.106.93.94 */
 /* interface. Note that this IP_ADD_MEMBERSHIP option must be */
 /* called for each local interface over which the multicast */
 /* datagrams are to be received. */
 group.imr_multiaddr.s_addr = inet_addr("226.1.1.1");
 group.imr_interface.s_addr = htonl(INADDR_ANY);
 if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
 {
  perror("Adding multicast group error");
  close(sd);
  exit(1);
 }
 /* Read from the socket. */
 datalen = sizeof(databuf);
 if(read(sd, databuf, datalen) < 0)
 {
  perror("Reading datagram message error");
  close(sd);
  exit(1);
 }
 else
  printf("The message from multicast client is: %s\n", databuf);
 return 0;
}
阅读(1045) | 评论(0) | 转发(0) |
0

上一篇:Quoted-Printable编码实现

下一篇:raw socket

给主人留下些什么吧!~~