udp socket客户端和udp服务端程序示例分享

时间:2021-05-19

Udp Socket

复制代码 代码如下:
#include <WinSock2.h>
#include <stdio.h>
#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 <WinSock2.h>
#include <stdio.h>

#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 lisi\n";
sendto(sockClient, sendBuf, strlen(sendBuf)+1,0, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));

// close connection socket
closesocket(sockClient);

// clean socket library
WSACleanup();
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章