windows 下 udp socket通信
server.c
#include <stdio.h>
#include <winsock2.h>
#include <Windows.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 6000
int main(int argc, char* argv[])
{
//初始化网络环境
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("WSAStartup failed\n");
return -1;
}
//建立一个UDP的socket
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == SOCKET_ERROR)
{
printf("create socket failed\n");
return -1;
}
//绑定地址信息
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(sock, (struct sockaddr*)&serverAddr, sizeof(struct sockaddr));
char buf[512];
while (TRUE)
{
memset(buf, 0, 512);
// 网络节点的信息,用来保存客户端的网络信息
struct sockaddr_in clientAddr;
memset(&clientAddr, 0, sizeof(struct sockaddr_in));
int clientAddrLen = sizeof(struct sockaddr);
//接收客户端发来的数据
int ret = recvfrom(sock, buf, 512, 0,(struct sockaddr*) &clientAddr,&clientAddrLen );
printf("Recv msg:%s from IP:[%s] Port:[%d]\n", buf,inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port));
// 发一个数据包返回给客户
sendto(sock, "Hello World!", strlen("Hello World!"), 0, (struct sockaddr*)&clientAddr, clientAddrLen);
printf("Send msg back to IP:[%s] Port:[%d]\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
}
return 0;
}
client.c
#include <stdio.h>
#include <winsock2.h>
#include <Windows.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 6000
int main(int argc, char* argv[])
{
//初始化网络环境
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("WSAStartup failed\n");
return -1;
}
//建立一个UDP的socket
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockClient == INVALID_SOCKET)
{
printf("create socket failed\n");
return -1;
}
// 申明一个网络地址信息的结构体,保存服务器的地址信息
struct sockaddr_in addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
// addr.sin_port = htons(10014);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
char buf[] = "client test!";
//发送数据
int dwSent = sendto(sockClient, buf, strlen(buf), 0, (SOCKADDR *)&addr, sizeof(SOCKADDR));
if (dwSent == 0)
{
printf("send %s failed\n", buf);
return -1;
}
printf("send msg:%s\n", buf);
char recvBuf[512];
memset(recvBuf, 0, 512);
struct sockaddr_in addrSever = { 0 };
int nServerAddrLen=sizeof(struct sockaddr_in);
// 接收数据
int dwRecv = recvfrom(sockClient, recvBuf, 512, 0, (SOCKADDR *)&addrSever,&nServerAddrLen);
printf("Recv msg from server : %s\n", recvBuf);
//关闭SOCKET连接
closesocket(sockClient);
//清理网络环境
WSACleanup();
system("pause");
return 0;
}
编译
gcc server.c -o server.exe -lws2_32
gcc client.c -o client.exe -lws2_32
#运行
./server.exe
./client.exe
本文来自博客园踩坑狭,作者:韩若明瞳,转载请注明原文链接:https://www.cnblogs.com/han-guang-xue/p/15846975.html