欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

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

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

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

上一篇:使用单链表实现多项式计算示例

栏    目:C语言

下一篇:linux系统中c++写日志文件功能分享

本文标题:udp socket客户端和udp服务端程序示例分享

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/3730.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有