- Introduction of header file, import lib file
#include <stdio.h> #include <stdlib.h > #include <string.h> #include < Winsock2.h> #pragma comment (lib, "Ws2_32.lib") 2. Declared in the header file because C code in C + + needs to use the extern keyword
extern "C"
{
int Socket_send ();
int Socket_recv ();
}
3. 发送方的实现
int Socket_send ()&NBSP;
{&NBSP;
//Initialize Socket&NBSP;
DWORD ver; Wsadata wsadata; SOCKET st;
size_t rc; unsigned long laddr;
struct sockaddr_in addr; Char buf[1024]={0};
Ver=makeword;//Call Wsasatup to tell Windows which version to use Scoket&NBSP;
WSAStartup (Ver,&wsadata); As long as the socket is used, this method must be called, Windows rules &NBSP;
//Initialize Scoket finish
St=socket (af_inet,sock_dgram,0); Establish a socket//struct sockaddr_in addr;memset (&addr,0,sizeof (addr)); addr.sin_family=af_inet;addr.sin_port= Htons (8080); Addr.sin_addr.s_addr=inet_addr ("127.0.0.1");
/* laddr=inet_addr ("192.168.6.200"); &NBSP;
printf ("%x\n", laddr); */ strcpy (buf, "Hello World") Rc=sendto (St,buf,strlen (BUF), 0, (struct sockaddr *) &addr,sizeof (addr)); printf ("Sender%s\n", buf); Closesocket (ST); WSACleanup (); Return rc; &NBSP
}
4. 接收方的实现
int Socket_recv ()&NBSP;
{&NBSP;
//Initialize Socket&NBSP;
DWORD ver; Wsadata wsadata; SOCKET st;
size_t rc; unsigned long laddr;
struct sockaddr_in addr; Char buf[1024]={0};
Ver=makeword;//Call Wsasatup to tell Windows which version to use Scoket&NBSP;
WSAStartup (Ver,&wsadata); As long as the socket is used, this method must be called, Windows rules &NBSP;
//Initialize Scoket finish
St=socket (af_inet,sock_dgram,0); Establish a socket//struct sockaddr_in addr;memset (&addr,0,sizeof (addr)); addr.sin_family=af_inet;addr.sin_port= Htons (8080); addr.sin_addr.s_addr=htonl (Inaddr_any); As the receiver does not need to specify the specific IP address if (bind (ST, struct sockaddr *) &addr,sizeof (addr)) >-1)//port number with program binding {struct sockaddr_in send _ADDR; int Len; memset (&send_addr,0,sizeof (SEND_ADDR)); Len=sizeof (SEND_ADDR); Receive UDP Data Rc=recvfrom (st,buf,sizeof (BUF), 0, (struct sockaddr *) &send_addr,&len); Rc=sendto (St,buf,strlen (BUF), 0, (struct sockaddr *) &addr,sizeof (addr)); printf ("Receiving Party%s\n", BUF);} Closesocket (ST); WSACleanup (); return RC;
}
5. 最后一步,在C++中的调用
int main (int argc,char *args[])
{
int i=0,j=0;
if (argc>1)
{
if (args[1][0]== ' 1 ')
{
cout<< "Send" <
* * Results of Operation * *
Encapsulating the UDP protocol using C and C + + mixed programming