UDP SERVER
// UDP通信_SERVER.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib,"WS2_32.LIB")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
SOCKET recvsock;
sockaddr_in addr;
int len=sizeof(sockaddr_in);
WSAStartup(MAKEWORD(2,2),&wsadata);
recvsock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
addr.sin_family=AF_INET;
addr.sin_port=htons(1999);
addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
bind(recvsock,(sockaddr*)&addr,sizeof(addr));
char buf[1024];
sockaddr_in sendaddr;
cout<<"Receiving datagrams...\n";
int value=recvfrom(recvsock,buf,1024,0,(sockaddr*)&sendaddr,&len);
//1.接收套接字 2.存放所接收数据的地址 3.数据地址长度 4.客户端地址 5.客户端地址长度
if(value==SOCKET_ERROR)
{
cout<<"recvfrom failed"<<endl;
closesocket(recvsock);
WSACleanup();
return -1;
}
//输出系统时间
SYSTEMTIME st;
GetLocalTime(&st);
cout<<st.wYear<<"-"<<st.wMonth<<"-"<<st.wDay<<" "<<st.wHour<<":"<<st.wMinute<<":"<<st.wSecond<<"\t";
cout<<inet_ntoa(sendaddr.sin_addr)<<":"<<ntohs(sendaddr.sin_port)<<" "<<buf<<endl;
//inet_ntoa将一个IP转换成一个互联网标准点分格式的字符串。// inet_addr将一个点间隔地址转换成一个in_addr。
closesocket(recvsock);
WSACleanup();
if(getchar())
return 0;
return 0;
}
//套接字与地址绑定完毕
UDP CLIENT
// UDP通信Client.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib,"WS2_32.LIB")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsa;
WSAStartup(MAKEWORD(2,2,),&wsa);
SOCKET sendsock;
sendsock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
SOCKADDR_IN addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(1999);
addr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
char buf[1024]="if you get it ,that means you have receive it sucessfully!";
int value=sendto(sendsock,buf,1024,0,(sockaddr*)&addr,sizeof(addr));
if(value==SOCKET_ERROR)
{
cout<<"sendto function failed.\n";
closesocket(sendsock);
WSACleanup();
return -1;
}
else
cout<<buf<<" has been send successfully."<<endl;
closesocket(sendsock);
WSACleanup();
if(getchar())
return 0;
}
//套接字初始化成功后,直接就可以sendto发送信息,客户端不需要bind()