用Visual C++编程实现局域网多播

最近一直在看<<Unix网络编程>>这本书,觉得这本书很适合初学socket编程的人。我一直对于多播的实现比较模糊,在看了书上的多播部分的介绍,才发现在程序中实现一个基本的多播功能是如此简单。

    在这里我不想照本宣科的大说什么理论,概念的东东,我的目的是说明在我们的代码中如何实现多播功能。

    开发环境: VC 6.0(sp5), 使用winsock2(ws2_32.lib)

    测试环境: 三台机器位于两个不同的AD域中,所有机器都是windows 2000(SP4)的操作系统。 sz09和kenfilweb4位于域kenfilszwin2k, kenfil-sz18是域sz18-domain域的一台DC.

    对于局域网来说,我们可以使用的多播地址为224.0.0.0-224.0.0.255(想知道为什么?看看书吧。:-) )

    多播是通过设置套接口(socket, 来自书上的翻译)选项来实现的,这个套接口必须是一个UDP的套接口

    IP_ADD_MEMBERSHIP: 加入一个多播组

    IP_DROP_MEMBERSHIP: 离开一个多播组

    IP_MULTICAST_IF: 指定外出多播数据报的外出接口

    IP_MULTICAST_TTL: TTL数

    IP_MULTICAST_LOOP: 是否禁止回馈,我的理解是一台机器是否可以接收到自己发送的多播数据报

    在设置IP_ADD_MEMBERSHIP和IP_DROP_MEMBERSHIP选项的时候,我们需要用到ip_mreq结构, 要使用此结构,你必须include <Ws2tcpip.h>, 并确保此include位于include <winsock2.h>之下

    程序功能:程序读取用户输入的行发送到多播组,加入多播组的任何客户端应该显示从多播组中读到的数据。

    实现代码如下:

 //Project Setting -> C/C++ -> Code Generation -> 确认选中"Debug Multithreaded"
#include <iostream>
#include <winsock2.h> //注意这里的include文件顺序
#include <Ws2tcpip.h>
#include <process.h> //_beginthread要求
#pragma comment(lib, "ws2_32.lib")
using namespace std;
const char* MULTICAST_IP = "224.0.0.99"; //多播组地址
const int MULTICAST_PORT = 2002; //多播组端口
const int BUFFER_SIZE = 1024;
void do_send(void* arg); //读取用户输入并发送到多播组线程函数
void do_read(void* arg); //读物多播组数据函数
int main()
{
WSAData wsaData;
if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 )
{
cout<<"Error in WSAStartup"<<endl;
return 0;
}
SOCKET server;
server = socket(AF_INET, SOCK_DGRAM, 0); //创建一个UDP套接口
cout<<"create socket: "<<server<<endl;
int ret ;
const int on = 1; //允许程序的多个实例运行在同一台机器上
ret = setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
if( ret == SOCKET_ERROR )
{
WSACleanup();
cout<<"Error in setsockopt(SO_REUSEADDR): "<<WSAGetLastError()<<endl;
return 0;
}
const int routenum = 10;
ret = setsockopt(server,IPPROTO_IP,IP_MULTICAST_TTL,
(char*)&routenum,sizeof(routenum));
if( ret == SOCKET_ERROR )
{
WSACleanup();
cout<<"Error in setsockopt(IP_MULTICAST_TTL): "<<WSAGetLastError()<<endl;
return 0;
}
const int loopback = 0; //禁止回馈
ret = setsockopt(server,IPPROTO_IP,IP_MULTICAST_LOOP,
(char*)&loopback,sizeof(loopback));
if( ret == SOCKET_ERROR )
{
WSACleanup();
cout<<"Error in setsockopt(IP_MULTICAST_LOOP): "<<WSAGetLastError()<<endl;
return 0;
}
sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(MULTICAST_PORT);
local.sin_addr.S_un.S_addr = INADDR_ANY;
ret = bind(server, (sockaddr*)(&local), sizeof(local));
if( ret == SOCKET_ERROR )
{
WSACleanup();
cout<<"Error in bind: "<<WSAGetLastError()<<endl;
return 0;
}
ip_mreq mreq;
memset(&mreq, 0, sizeof(mreq));
mreq.imr_interface.S_un.S_addr = INADDR_ANY;
mreq.imr_multiaddr.S_un.S_addr = inet_addr(MULTICAST_IP);
//加入一个多播组
ret = setsockopt(server,IPPROTO_IP,IP_ADD_MEMBERSHIP,
(char*)&mreq,sizeof(mreq));
if( ret == SOCKET_ERROR )
{
WSACleanup();
cout<<"Error in setsockopt(IP_ADD_MEMBERSHIP): "<<WSAGetLastError()<<endl;
return 0;
}
//创建了两个线程,一个读用户输入并发送,一个读多播组数据
HANDLE hHandle[2];
hHandle[0] = (HANDLE)_beginthread(do_send,0,(void*)server);
hHandle[1] = (HANDLE)_beginthread(do_read,0,(void*)server);
//如果用户输入结束,程序就终止了
WaitForSingleObject(hHandle[0], INFINITE);
WSACleanup();
return 0;
}
void do_send(void* arg)
{
SOCKET server = (SOCKET)arg;
char sendline[BUFFER_SIZE+1];
sockaddr_in remote;
memset(&remote, 0, sizeof(remote));
remote.sin_addr.s_addr = inet_addr ( MULTICAST_IP );
remote.sin_family = AF_INET ;
remote.sin_port = htons(MULTICAST_PORT);
for(;;) //读取用户输入知道用户输入"end"
{
cin.getline(sendline, BUFFER_SIZE);
if(strncmp(sendline,"end",3)==0)
break;
//发送用户输入的数据到多播组
sendto(server, sendline, strlen(sendline), 0, (sockaddr*)(&remote), sizeof(remote));
}
cout<<"do_send end..."<<endl;
}
void do_read(void* arg)
{
SOCKET server = (SOCKET)arg;
char buf[BUFFER_SIZE+1];
int ret;
sockaddr_in client;
int clientLen;
for(;;) //一直读取知道主线程终止
{
clientLen = sizeof(client);
memset(&client, 0, clientLen);
ret = recvfrom(server, buf, BUFFER_SIZE, 0, (sockaddr*)(&clientLen), &clientLen);
if ( ret == 0) //do_read在用户直接回车发送了一个空字符串
{
continue;
}
else if( ret == SOCKET_ERROR )
{
if( WSAGetLastError() == WSAEINTR ) //主线程终止recvfrom返回的错
break;
cout<<"Error in recvfrom: "<<WSAGetLastError()<<endl;
break ;
}
buf[ret] = '';
cout<<"received: "<<buf<<endl;
}
cout<<"do_read end..."<<endl;
}

    当然上面的代码如果应用到实际的程序中还需要作更多的工作,不过实现多播功能真的很简单,不是吗?
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
网络课程设计用 Visual C++实现局域网 IP 多播 // task3UIDlg.cpp : implementation file // #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <stdlib.h> #include <String.h> #pragma comment(lib,"ws2_32") #include "StdAfx.h" #include "task3UI.h" #include "task3UIDlg.h" #include "../task3UI/CInitSock.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MCASTADDR "233.0.0.1" //本例使用的多播组地址。 #define MCASTPORT 9999 //本地端口号。 #define BUFSIZE 1024 //发送数据缓冲大小。 WSADATA wsd; struct sockaddr_in local,remote,from; SOCKET sock,sockM; TCHAR sendbuf[BUFSIZE]; TCHAR recvbuf[BUFSIZE]; char ip[255]; int len; CString strrece,strsend; int CTask3UIDlg::KMeansSegment() { // 主要处理函数在这里写 int ret; while(1){ if(( ret = recvfrom(sock,recvbuf,BUFSIZE,0,(struct sockaddr*)&from;,&len;)) == SOCKET_ERROR) { printf("recvfrom failed with:%d\n",WSAGetLastError()); closesocket(sockM); closesocket(sock); WSACleanup(); return -1; } if( strcmp(recvbuf,"QUIT") == 0 ) { break; }else{ recvbuf[ret] = '\0'; if(strcmp(ip,inet_ntoa(from.sin_addr))!=0){ printf("%s : %s\n",inet_ntoa(from.sin_addr),recvbuf); GetDlgItemText(IDC_RECE,strrece); SetDlgItemText(IDC_RECE,strrece+inet_ntoa(from.sin_addr)+":"+recvbuf+"\r\n"); } } } return 0L; } UINT myproc(LPVOID lParam) { CTask3UIDlg *pWnd = (CTask3UIDlg *)lParam; //将窗口指针赋给无类型指针 pWnd->KMeansSegment(); //要执行的函数 return 1; } bool GetLocalIP(char* ip) { char szText[256]; //获取本机主机名称 int iRet; iRet = gethostname(szText,256); int a = WSAGetLastError(); if (iRet!=0) { printf("gethostname() Failed!"); return FALSE; } //通过主机名获取到地址信息 HOSTENT *host = gethostbyname(szText); if (NULL==host) { printf("gethostbyname() Failed!"); return false; } in_addr PcAddr; for (int i=0;;i++) { char *p = host->h_addr_list[i]; if (NULL==p) { break; } memcpy(&(PcAddr.S_un.S_addr),p,host->h_length); ip = ::inet_ntoa(PcAddr); } return true; } int chushihua() { len = sizeof( struct sockaddr_in); //初始化 WinSock2.2 if( WSAStartup( MAKEWORD(2,2),&wsd;) != 0 ) { printf("WSAStartup() failed\n"); return -1; } if((sock=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0, WSA_FLAG_MULTIPOINT_C_LEAF|WSA_FLAG_MULTIPOINT_D_LEAF| WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET) { printf("socket failed with:%d\n",WSAGetLastError()); WSACleanup(); return -1; } //将 sock 绑定到本机某端口上。 local.sin_family = AF_INET; local.sin_port = htons(MCASTPORT); local.sin_addr.s_addr = INADDR_ANY; if( bind(sock,(struct sockaddr*)&local;,sizeof(local)) == SOCKET_ERROR ) { printf( "bind failed with:%d \n",WSAGetLastError()); closesocket(sock); WSACleanup(); return -1; } //加入多播组 remote.sin_family = AF_INET; remote.sin_port = htons(MCASTPORT); remote.sin_addr.s_addr = inet_addr( MCASTADDR ); if(( sockM = WSAJoinLeaf(sock,(SOCKADDR*)&remote;, sizeof(remote),NULL,NULL,NULL,NULL, JL_BOTH)) == INVALID_SOCKET) { printf("WSAJoinLeaf() failed:%d\n",WSAGetLastError()); closesocket(sock); WSACleanup(); return -1; } } int mainmain() { //发送多播数据,当用户在控制台输入"QUIT"时退出。 //while(1) //{ //scanf("%s",sendbuf); if( sendto(sockM,(char*)sendbuf,strlen(sendbuf),0,(struct sockaddr*) &remote;,sizeof(remote))==SOCKET_ERROR) { printf("sendto failed with: %d\n",WSAGetLastError()); closesocket(sockM); closesocket(sock); WSACleanup(); return -1; } //if(strcmp(sendbuf,"QUIT")==0) break; //Sleep(500); //} /*closesocket(sockM); closesocket(sock); WSACleanup();*/ return 0; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP(); }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTask3UIDlg dialog CTask3UIDlg::CTask3UIDlg(CWnd* pParent /*=NULL*/) : CDialog(CTask3UIDlg::IDD, pParent) { //{{AFX_DATA_INIT(CTask3UIDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CTask3UIDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTask3UIDlg) DDX_Control(pDX, IDC_RECE, m_Edit); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTask3UIDlg, CDialog) //{{AFX_MSG_MAP(CTask3UIDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_tishi, Ontishi) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTask3UIDlg message handlers BOOL CTask3UIDlg::OnInitDialog() { CDialog::OnInitDialog(); chushihua(); GetLocalIP(ip); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon AfxBeginThread(myproc, (LPVOID)this); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CTask3UIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CTask3UIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect;); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CTask3UIDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CTask3UIDlg::OnOK() { //CString strrece,strsend; // TODO: Add your control notification handler code here GetDlgItemText(IDC_SEND,strsend); strcpy(sendbuf, strsend); mainmain(); } void CTask3UIDlg::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); } void CTask3UIDlg::Ontishi() { // TODO: Add your control notification handler code here } void CTask3UIDlg::Onsend() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值