C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > udp服务端程序

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

作者:

这篇文章主要介绍了udp socket客户端和udp服务端程序示例,需要的朋友可以参考下

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();
}

您可能感兴趣的文章:
阅读全文