首页 > 其他 > 详细

UDP通信

时间:2014-02-07 21:51:11      阅读:381      评论:0      收藏:0      [点我收藏+]

建立UDP通信,服务器的端的代码如下:

#include <Winsock2.h>
#include <iostream>
using namespace std;
#include <stdio.h>
#pragma   comment(lib,"Ws2_32.lib")  
void GetIP(void) 
{ 
char host_name[255]; 
gethostname(host_name, sizeof(host_name)); 
cout<<"本机主机名为:"<<"  "<<host_name<<endl<<endl; 
struct hostent *phe = gethostbyname(host_name);
											
struct in_addr addr;							
memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
char *ip=inet_ntoa(addr);//网络地址格式转换
cout<<"本机IP地址为:"<<"  "<<ip<<endl;
} 

int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(2,0);
err=WSAStartup(wVersionRequested,&wsaData);
if(0!=err)
{
cout<<"Socket2.0 初始化失败"<<endl;
return -1;
}
if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wVersion)!=0)
{
WSACleanup();
return -1;
}

GetIP();
SOCKET sockConn=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockConn,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
int len=sizeof(SOCKADDR);
while(1)
{
printf("客户端信息: ");
char recvBuf[1000];
recv(sockConn,recvBuf,1000,0);
puts(recvBuf);
}
if(!closesocket(sockConn))
{
WSAGetLastError();
return -1;
}
if(!WSACleanup())
{
WSAGetLastError();
return -1;
}
return 0; 
}


客户端的代码:

#include <Winsock2.h>
#include <iostream>
using namespace std;
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib") 
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(2,0);
err=WSAStartup(wVersionRequested,&wsaData);
if(0!=err)
{
cout<<"Socket2.0 初始化失败"<<endl;
return -1;
}

if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wVersion)!=0)
{
WSACleanup();
return -1;
}

char str[100];
cout<<"输入要连接的主机的IP地址:"<<endl;
gets(str);
int m;
cout<<"输入要连接的主机的端口号:"<<endl;
cin>>m;
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr(str);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(m);
int len=sizeof(SOCKADDR);
while(1)
{
printf("要发送的信息请输入: ");
char sendBuf[1000];
gets(sendBuf);
sendto(sockClient,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR*)&addrSrv,len);
}
if(!closesocket(sockClient))
{
WSAGetLastError();
return -1;
}
if(!WSACleanup())
{
WSAGetLastError();
return -1;
}
return 0;
}






UDP通信

原文:http://blog.csdn.net/u011608357/article/details/18963009

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!