标签:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#pragma comment(lib,"Ws2_32.lib")
2. 在头文件中声明,由于是C++中调用C代码需要使用extern关键字
extern “C”
{
int socket_send();
int socket_recv();
}
3. 发送方的实现
int socket_send()
{
//初始化socket
DWORD ver;
WSADATA wsadata;
SOCKET st;
size_t rc;
unsigned long laddr;
struct sockaddr_in addr;
char buf[1024]={0};
ver=MAKEWORD(1,1); //调用wsaSatup时要告诉windows要使用哪个版本scoket
WSAStartup(ver,&wsadata); //只要使用socket,必须调用这个方法,WINDOWS规定
//初始化scoket完成
st=socket(AF_INET,SOCK_DGRAM,0); //建立一个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”);
printf(“%x\n”,laddr);*/
strcpy(buf,”Hello World”);
rc=sendto(st,buf,strlen(buf),0,(struct sockaddr *)&addr,sizeof(addr));
printf(“发送方%s\n”,buf);
closesocket(st);
WSACleanup();
return rc;
}
4. 接收方的实现
int socket_recv()
{
//初始化socket
DWORD ver;
WSADATA wsadata;
SOCKET st;
size_t rc;
unsigned long laddr;
struct sockaddr_in addr;
char buf[1024]={0};
ver=MAKEWORD(1,1); //调用wsaSatup时要告诉windows要使用哪个版本scoket
WSAStartup(ver,&wsadata); //只要使用socket,必须调用这个方法,WINDOWS规定
//初始化scoket完成
st=socket(AF_INET,SOCK_DGRAM,0); //建立一个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); //作为接收方不需要指定具体的IP地址
if(bind(st,(struct sockaddr *)&addr,sizeof(addr))>-1) //将端口号与程序绑定
{
struct sockaddr_in send_addr;
int len;
memset(&send_addr,0,sizeof(send_addr));
len=sizeof(send_addr);
//接收UDP数据
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("接收方%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<<”发送”<
标签:
原文地址:http://www.cnblogs.com/jjx2013/p/5186335.html