嵌入式视频行业。
分类: C/C++
2008-09-25 20:28:09
#include "winsock2.h"
#include "iostream.h"
#pragma comment(lib,"ws2_32.lib")
void InitWinsock2();
void BindUDPSock(SOCKET*);
void RecieveUDP(SOCKET*);
void SendUDP(LPVOID,int);
void main()
{
InitWinsock2(); //初始化套接字
SOCKET sockSrv=socket(AF_INET,SOCK_DGRAM,0); //建立套接字
BindUDPSock(&sockSrv); //绑定套接字
// RecieveUDP(&sockSrv); //接收UDP数据
//发送UDP数据
char tmp[20]="shenzhouqihao";
int len=sizeof(tmp);
SendUDP(tmp,len);
}
//初始化套接字
void InitWinsock2()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2 , 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
}
//绑定套接字
void BindUDPSock(SOCKET* socket)
{
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); //本机接收的IP地址源
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000); //本机接收端口
bind(*socket,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
}
//接收UDP数据
void RecieveUDP(SOCKET *socket)
{
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
char recvBuf[100]={0};
if(SOCKET_ERROR!=recvfrom(*socket,recvBuf,100,0,(SOCKADDR*)&addrClient,&len))
cout<<recvBuf<<endl;
}
}
//发送UDP数据包
void SendUDP(LPVOID comment,int len)
{
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); //接收方IP
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000); //接收方端口
sendto(sockClient,(char *)comment,len,0,
(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
}