C 语言 devc++ 使用 winsock 实现 windows UDP 利用 IP 进行局域网发送消息

UDP 通信流程_udp通信过程-CSDN博客参考来源

UDP 通信流程_udp通信过程-CSDN博客

这里移植到windows 上 ,使用 devc++ 开发。

服务端代码

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>

int main()
{
	WORD sockVersion = MAKEWORD(2, 2);
	WSADATA data;
	if (WSAStartup(sockVersion, &data) != 0)
	{
		return 0;
	}
	// 1. 创建通信的套接字
	SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd == INVALID_SOCKET)
	{
		printf("无效的 socket !");
		return 0;
	}

	// 2. 通信的套接字和本地的IP与端口绑定
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(9999);    // 大端
	addr.sin_addr.s_addr = htonl(INADDR_ANY);  // 0.0.0.0
	int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
	if(ret == -1)
	{
		perror("bind");
		exit(0);
	}

	char buf[1024];
	struct sockaddr_in cliaddr;
	int len = sizeof(cliaddr);
	// 3. 通信
	while(1)
	{
		// 接收数据
		memset(buf, 0, sizeof(buf));
		int rlen = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&cliaddr, &len);
		printf("客户端的IP地址: %s, 端口: %d\n",
		       inet_ntoa(cliaddr.sin_addr),
		       ntohs(cliaddr.sin_port));
		printf("客户端say: %s\n", buf);

		// 回复数据
		// 数据回复给了发送数据的客户端
		sendto(fd, buf, rlen, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
	}

	close(fd);

	return 0;
}

客户端代码

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>

int main()
{
	WORD sockVersion = MAKEWORD(2, 2);
	WSADATA data;
	if (WSAStartup(sockVersion, &data) != 0)
	{
		return 0;
	}
	// 1. 创建通信的套接字
	SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd == INVALID_SOCKET)
	{
		printf("无效的 socket !");
		return 0;
	}

	// 2. 通信的套接字和本地的IP与端口绑定
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(9999);    // 大端
//	addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);  // 255.255.255.255 广播 
	char loa[16] = "127.0.0.1";						// 这是指定 IP发送数据 
	addr.sin_addr.S_un.S_addr = inet_addr(loa);				// 加入指定 IP 


	char buf[1024];
    char ipbuf[64];
    int num = 0;
    // 2. 通信
    while(1)
    {
        sprintf(buf, "hello, udp %d....\n", num++);
        // 发送数据, 数据发送给了服务器
        sendto(fd, buf, strlen(buf)+1, 0, (struct sockaddr*)&addr, sizeof(addr));
 
        // 接收数据
        memset(buf, 0, sizeof(buf));
        recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
        printf("服务器say: %s\n", buf);
        sleep(1);
    }
 
    close(fd);
 
    return 0;
}
相关推荐
YuMiao20 小时前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_4 天前
高可用移动网络连接
网络协议
chilix4 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅6 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19986 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205526 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel6 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)6 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~6 天前
Debian系统如何删除多余的kernel
linux·网络·debian