⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 send_udp_packetdlg.cpp

📁 发送UDP网络数据包
💻 CPP
字号:
// Send_UDP_PacketDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Send_UDP_Packet.h"
#include "Send_UDP_PacketDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
int flag=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()

/////////////////////////////////////////////////////////////////////////////
// CSend_UDP_PacketDlg dialog

CSend_UDP_PacketDlg::CSend_UDP_PacketDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSend_UDP_PacketDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CSend_UDP_PacketDlg)
    m_IPAddr = _T("192.168.2.37");
    m_PacketSize = 500;
    m_String = _T("I love you!!!");
    m_locip = _T("");
    m_DstPort = 6800;
    m_DelayTime = 10;
    m_Times = 100;
    m_szSend = _T("");
	//}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    static	flag=1;
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSend_UDP_PacketDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CSend_UDP_PacketDlg)
    DDX_Control(pDX, IDC_LISTCTL, m_ListCtl);
    DDX_Control(pDX, IDC_PROGRESS1, m_CtrlPro);
    DDX_Text(pDX, IDC_EDIT1, m_IPAddr);
    DDV_MaxChars(pDX, m_IPAddr, 15);
    DDX_Text(pDX, IDC_EDIT6, m_PacketSize);
    DDX_Text(pDX, IDC_EDIT7, m_String);
    DDX_Text(pDX, IDC_EDIT8, m_locip);
    DDX_Text(pDX, IDC_EDIT3, m_DstPort);
    DDX_Text(pDX, IDC_EDIT4, m_DelayTime);
    DDX_Text(pDX, IDC_EDIT5, m_Times);
    DDX_Text(pDX, IDC_EDIT2, m_szSend);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSend_UDP_PacketDlg, CDialog)
//{{AFX_MSG_MAP(CSend_UDP_PacketDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_TIMER()
ON_BN_CLICKED(IDC_Openfile, OnOpenfile)
ON_BN_CLICKED(IDC_ContinuousSend, OnContinuousSend)
ON_BN_CLICKED(IDC_ContinualSend, OnContinualSend)
	ON_BN_CLICKED(IDC_StartReceive, OnStartReceive)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSend_UDP_PacketDlg message handlers

BOOL CSend_UDP_PacketDlg::OnInitDialog()
{
    CDialog::OnInitDialog();  ////carry out the father default  initialize dialog   
    
    column.mask=LVCF_FMT|LVCF_WIDTH|LVCF_TEXT|LVCF_SUBITEM;
    column.fmt=LVCFMT_LEFT;
    column.cx=50;
    
    column.iSubItem=0;
    column.pszText="Number";
    m_ListCtl.InsertColumn(0,&column);
    
    column.cx=90;
    column.iSubItem=1;
    column.pszText="Source IP";
    m_ListCtl.InsertColumn(1,&column);
    
    column.cx=80;
    column.iSubItem=2;
    column.pszText="Source Port";
    m_ListCtl.InsertColumn(2,&column);
    
    column.iSubItem=3;
    column.pszText="Packet Size";
    m_ListCtl.InsertColumn(3,&column);
    
    column.cx=655;
    column.iSubItem=4;
    column.pszText="Content";
    m_ListCtl.InsertColumn(4,&column);
    
    
    item.mask=LVIF_TEXT;
    
    
    char szHostName[128]; 
    
    if( gethostname(szHostName, 128) == 0 ) 
    { 
        // Get host adresses 
        struct hostent * pHost; 
        int i; 
        
        pHost = gethostbyname(szHostName); 
        
        for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) 
        { 
            CString str; 
            int j; 
            
            for( j = 0; j < pHost->h_length; j++ ) 
            { 
                CString addr; 
                
                if( j > 0 ) 
                    str += "."; 
                
                addr.Format("%u", (unsigned int)((unsigned 
                    char*)pHost->h_addr_list[i])[j]); 
                str += addr; 
            } 
            
            m_locip=str;
            UpdateData(0);
        } 
        
    } 
    
    
    UpdateData(1);
    //creat local port 
    m_sockSend.Create(0,SOCK_DGRAM,NULL);  //Creat the socksend at given port,using the UDP(SOCK_DGRAM) protocol
    
    //bind local 
    m_sockSend.Bind(0,m_IPAddr); //Bind the destination IP & Port
    
    //创建本地套接口
    m_sockRecv.Create(m_DstPort,SOCK_DGRAM,m_locip);
    //绑定本地套接口
    m_sockRecv.Bind(m_DstPort,m_locip);
    
    
    SetTimer(1,100,NULL);
    
    propos = 0;  //set the OutofmemoryProgress start position
    m_CtrlPro.SetRange(0, 100);   //set the OutofmemoryProgress range
    m_CtrlPro.SetPos(0); //set the OutofmemoryProgress  current position
    
    down = true; 
	click = true;
    return TRUE; // return TRUE  unless you set the focus to a control
    
    
}

void CSend_UDP_PacketDlg::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 CSend_UDP_PacketDlg::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 CSend_UDP_PacketDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}



////////////////////////////////////////////////////////////////////////////

void CSend_UDP_PacketDlg::OnTimer(UINT nIDEvent) 
{
    if( nIDEvent == 1 )
    {
        if(flag%2==1)
        {
            UpdateData(1);
            SetTimer(1,m_DelayTime,NULL);
            if(m_Times<=0)
            {
                static iIndex=0;
                char szSend[20];
                sprintf(szSend,"%010d",iIndex++);
                
                //send UDP packet
				if( strlen(m_String) )
					int iSend= m_sockSend.SendTo(m_String,strlen(m_String),m_DstPort,m_IPAddr,0);
				else
					int iSend= m_sockSend.SendTo(m_String,m_PacketSize,m_DstPort,m_IPAddr,0);

                m_szSend=szSend;
                UpdateData(FALSE);
                CDialog::OnTimer(nIDEvent);
            }
            
            
            //set  process bar
            propos ++;
            if( propos % 100 == 0 )
                propos = 0;
            m_CtrlPro.SetPos(propos); 
        }		
    }
    
    char szRecv[65535];    
    CString szIP(m_locip);
    UINT uPort=6800;    
    
    //接收UDP数据
    int iRecv = m_sockRecv.ReceiveFrom(szRecv,strlen(szRecv),szIP,uPort,0);
    
    item.iItem=0;
    item.iSubItem=0;
	
    if( iRecv > 0 && !click ) {
		
		szRecv[iRecv]='\0';
		
        CString num;
        num.Format("%d", item.iItem);        
        item.pszText = num.GetBuffer(0);      
		
        
        m_ListCtl.InsertItem(&item);
        m_ListCtl.SetItemText(item.iItem,1,szIP);     //source ip
		
		CString port;
        port.Format("%d", uPort);
        m_ListCtl.SetItemText(item.iItem,2,port);      //source port
		
		CString size;
        size.Format("%d", iRecv);
		m_ListCtl.SetItemText(item.iItem,3,size);       //received packet size (byte)
		
		m_ListCtl.SetItemText(item.iItem,4,szRecv);		//content
		
		item.iItem++;
        
        UpdateData(FALSE);
    } 
    CDialog::OnTimer(nIDEvent);
}




/////////////////////////////////////////////////////////////////////////////
void CSend_UDP_PacketDlg::OnOpenfile() 
{
    // TODO: Add your control notification handler code here
    CFileDialog dlg(TRUE,"txt","*.txt");
    //    CFileDialog dlg(FALSE,"doc","*.doc");
    if(dlg.DoModal()!=IDOK)   //打开文件公用对话框
    {
        return;
    }	
    else
    {	byte buf[2];
    m_String="";
    CString file=dlg.GetPathName();	//取得文件对话框返回的文件绝对路径
    
    CFile f;
    f.Open(file,CFile::modeRead);
    int filesize=f.GetLength();//用CFile方式获取取得文件大小;
    f.Close();
    
    FILE *rd;
    rd=fopen(file,"r+b");//用文件流 二进制读方式打开
    for(int i=0;i<filesize;i++)
    {fread(buf,1,1,rd);
    m_String+=buf[0];	//将文本读到EDIT控件对应的变量中。
    }
    fclose(rd);
    UpdateData(0);//变量->控件 数据交换。
    }	
}

void CSend_UDP_PacketDlg::OnContinuousSend() 
{
    // TODO: Add your control notification handler code here
    UpdateData(1);
    flag+=1;
    
    if(flag%2)
    {  
        m_Times=0;
		
        UpdateData(0);
    }
    
    
    if( down )
    {
        down = false;
        GetDlgItem (IDC_ContinuousSend)->SetWindowText("Stop"); 
        
    }
    else
    {
        down = true;
        GetDlgItem (IDC_ContinuousSend)->SetWindowText("Start"); 
    }	
    SetTimer(2,100,NULL);
}

void CSend_UDP_PacketDlg::OnContinualSend() 
{
    // TODO: Add your control notification handler code here
    
    UpdateData(1);
    SetTimer(1,m_DelayTime,NULL);
    static Index=0;
    char szSend[20];
    
    static t=m_Times;
    sprintf(szSend,"%010d",m_Times+t);
    t+=m_Times;
    
    
    for(int i=0;i<m_Times;i++)
    {
        //send UDP packet
        int iSend= m_sockSend.SendTo(m_String,strlen(m_String),m_DstPort,m_IPAddr,0);
        //      TRACE("sent %d byte\n",iSend);
        m_szSend=szSend;
        
    }
    UpdateData(0);
    
    if(!(flag%2))
        for(int l=0;l<=100;l++) {
            m_CtrlPro.SetPos(l);
            Sleep(m_DelayTime);
        }
        
        GetDlgItem (IDC_ContinualSend)->SetWindowText("Start"); 
}


void CSend_UDP_PacketDlg::OnStartReceive() 
{
	// TODO: Add your control notification handler code here
	

  if( click )
    {
        click = false;
        GetDlgItem (IDC_StartReceive)->SetWindowText("Stop Receive"); 
        
    }
    else
    {
        click = true;
        GetDlgItem (IDC_StartReceive)->SetWindowText("Start Receive"); 
    }	

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -