这周主要做了udp组播的测试
服务器端代码:
//服务器发送端
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <linux/sockios.h>
#include <sys/ioctl.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
std::string HELLO_GROUP = "224.0.31.128";
int HELLO_PORT = 12345;
bool bRunning = true;
void handler(int signo)
{
if (signo == SIGINT ||
signo == SIGQUIT)
{
bRunning = false;
}
}
int main(int argc, char *argv[])
{
// 如果传参,就优先从参数中读取
if (argc > 1)
{
HELLO_GROUP = argv[1];
}
else
{
HELLO_GROUP = udp_ip;
}
if (argc > 2)
{
HELLO_PORT = atoi(argv[2]);
}
signal(SIGPIPE, handler);
signal(SIGINT, handler);
signal(SIGHUP, handler);
signal(SIGTERM, handler);
signal(SIGCHLD, handler);
signal(SIGTSTP, handler);
signal(SIGQUIT, handler);
struct sockaddr_in addr;
int fd, cnt;
struct ip_mreq mreq;
char *message = "Hello, World!";
/* create what looks like an ordinary UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
//设置指定网卡名
if (interface_name.size() > 0)
{
struct ifreq interface;
strncpy(interface.ifr_ifrn.ifrn_name, interface_name.c_str(), interface_name.size());
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&interface, sizeof(interface)) < 0) {
perror("SO_BINDTODEVICE failed"