Csocket programming UDP in VC

Source: Internet
Author: User

When UDP sends data:

Csocket m_sendsock; // defines a network socket.

M_sendsock.close ();
Char szhostname [128] = {0 };
Gethostname (szhostname, 128 );
Hostent * phostent = gethostbyname (szhostname );
Char * pszip = inet_ntoa (* (in_addr *) & phostent-> h_addr_list [2]);
Cstring szport; // obtain the local port
M_port.getwindowtext (szport );
Int nport = atoi (szport );
If (! M_sendsock.create (nport, sock_dgram, pszip ))
{
MessageBox ("failed to create socket ");
}
Else
{
Bool bcmdopt = true;
M_sendsock.setsockopt (so_broadcast, (void *) & bcmdopt, 1); // set the socket to broadcast socket
 
Cstring szsendinfo; // sending information
Cstring szsendport; // The sending port.
M_sendcontent.getwindowtext (szsendinfo); // get the sending information
M_sendport.getwindowtext (szsendport );
Int nsendport = atoi (szsendport );
Sockaddr_in ADDR;
ADDR. sin_family = af_inet;
ADDR. sin_addr.s_un.s_addr = inaddr_broadcast;
ADDR. sin_port = htons (nsendport );
M_sendsock.sendto (szsendinfo. getbuffer (0), szsendinfo. getlength (),
(Sockaddr *) & ADDR, sizeof (ADDR ));
}

When UDP receives data:

// Obtain the IP address
Char szhostname [128];
Gethostname (szhostname, 128 );
Hostent * phostent = gethostbyname (szhostname );
Char * pszip = inet_ntoa (* (in_addr *) & phostent-> h_addr_list [2]);

M_localsock.setdialog (this );

M_localsock.create (8021, sock_dgram, pszip );

Bool bcmdopt = true;
M_localsock.setsockopt (so_broadcast, (void *) & bcmdopt, 1 );
Int nrecvnum = socket. receivefrom (pbuffer, 1024, szip, nport );
If (nrecvnum! =-1)
{
M_recvinfo.setwindowtext (pbuffer );
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.