建立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; }
原文:http://blog.csdn.net/u011608357/article/details/18963009