udp socket客户端和udp服务端程序示例分享
本文导语: Udp Socket 代码如下:#include #include #pragma comment(lib, "ws2_32.lib")int main(){// initial socket libraryWORD wVerisonRequested;WSADATA wsaData;int err;wVerisonRequested = MAKEWORD(1, 1);err = WSAStartup(wVerisonRequested, &wsaData);if (err != 0){return -1;}//if (LOBYTE(wsaData.wVersion) !...
Udp Socket
#include
#include
#pragma comment(lib, "ws2_32.lib")
int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}
// create socket
SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, 0);
// bind socket
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
bind(sockServer, (SOCKADDR *)&addrServer, sizeof(addrServer));
// receive
SOCKADDR_IN addrClient;
int len = sizeof(addrClient);
char recvBuf[100];
recvfrom(sockServer, recvBuf, 100, 0, (SOCKADDR *)&addrClient, &len);
printf("%s", recvBuf);
// close socket
closesocket(sockServer);
WSACleanup();
}
Udp Client
#include
#include
#pragma comment(lib, "ws2_32.lib")
int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}
// create socket
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
// send
char sendBuf[100] = "this is lisin";
sendto(sockClient, sendBuf, strlen(sendBuf)+1,0, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));
// close connection socket
closesocket(sockClient);
// clean socket library
WSACleanup();
}