- /* 发送端 */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <time.h>
- #include <string.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <net/if.h>
- #define TRAM_STATUS_ADDR 239.0.0.30
- #define TRAM_STATUS_RECV_PORT 9200
- int main(int argc, char **argv)
- {
- struct sockaddr_in addr, mcast_addr;
- int fd, cnt;
- struct ip_mreq mreq;
- int addrlen, num;
- char msg[32];
- sprintf(msg, "%s", "hello");
- if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
- {
- perror("socket");
- return -1;
- }
- memset(&mcast_addr, 0, sizeof(mcast_addr));
- mcast_addr.sin_family = AF_INET;
- mcast_addr.sin_addr.s_addr = inet_addr(TRAM_STATUS_ADDR);
- mcast_addr.sin_port = htons(TRAM_STATUS_RECV_PORT);
- if (sendto(fd, (const char *)msg, sizeof(msg), 0, (struct sockaddr *)&mcast_addr, sizeof(mcast_addr)) < 0)
- {
- perror("sendto");
- return -1;
- }
- printf("send ok!\n");
- setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mcast_addr, sizeof(mcast_addr));
- close(fd);
- return 0;
- }
- /* 接收端 */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <time.h>
- #include <string.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <sys/ioctl.h>
- #define MSGBUFSIZE 256
- #define TRAM_STATUS_ADDR 239.0.0.30
- #define TRAM_STATUS_RECV_PORT 9200
- int main()
- {
- struct sockaddr_in addr;
- int fd, nbytes, addrlen;
- struct ip_mreq mreq;
- char msgbuf[MSGBUFSIZE];
- int on;
- if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
- {
- perror("socket ");
- return -1;
- }
- /* 初始化地址 */
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = htonl(INADDR_ANY);
- addr.sin_port = htons(TRAM_STATUS_RECV_PORT);
- if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
- {
- perror("bind");
- return -1;
- }
- on = 1;
- /* 设置地址复用许可, 根据具体情况判断是否增加此功能 */
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
- {
- perror("SO_REUSEADDR");
- return -1;
- }
- /*加入多播组*/
- mreq.imr_multiaddr.s_addr = inet_addr(TRAM_STATUS_ADDR);
- mreq.imr_interface.s_addr = htonl(INADDR_ANY);
- if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)<br>
- {
- perror("setsockopt");
- return -1;
- }
- addrlen = sizeof(addr);
- if ((nbytes = recvfrom(fd, msgbuf, MSGBUFSIZE, 0, (struct sockaddr *)&addr, (socklen_t *)&addrlen)) < 0)
- {
- perror("recvfrom");
- return -1;
- }
- printf("recv ok!\n");
- /*退出多播组*/
- setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
- close(fd);
- return 0;
- }
- 以上两段程序均截取于已编译可正确执行的源代码,OS:Linux,在两个开发板之间进行组播测试。
Linux下UDP的组播接收和发送的简单例子
最新推荐文章于 2023-12-06 18:50:27 发布