UDP 客户端是windows版 服务端是linux 版
程序员文章站
2022-06-06 08:44:02
...
客户端
#include <iostream>
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll
#pragma warning(disable : 4996)
#define BUF_SIZE 100
int main() {
//初始化DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
//服务器地址信息
sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr)); //每个字节都用0填充
servAddr.sin_family = PF_INET;
// servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_addr.s_addr = inet_addr("192.168.8.4");
servAddr.sin_port = htons(65535);
//不断获取用户输入并发送给服务器,然后接受服务器数据
sockaddr fromAddr;
int addrLen = sizeof(fromAddr);
while (1)
{
char buff[BUF_SIZE] = { 0 };
printf("Input a string: ");
gets_s(buff);
sendto(sock, buff, strlen(buff), 0, (struct sockaddr*)&servAddr, sizeof(servAddr));
}
closesocket(sock);
WSACleanup();
return 0;
}
服务端
//1.创建udp通信socket
int udp_socket_fd=socket(AF_INET,SOCK_DGRAM,0);
int port=65535;
if(udp_socket_fd<0)
{
perror("create socket fail\n");
//return -1;
}
//2.设置UDP的地址并绑定
struct sockaddr_in local_addr ={0};
local_addr.sin_family=AF_INET; //使用IPv4协议
local_addr.sin_port=htons(port); //网络通信都使用大端格式
local_addr.sin_addr.s_addr=INADDR_ANY; //让系统检测本地网卡,自动绑定本地IP
int ret = bind(udp_socket_fd,(struct sockaddr*)&local_addr,sizeof(local_addr));
if(ret<0)
{
perror("bind fail:");
close(udp_socket_fd);
//return -1;
}
else
{
printf("recv ready!!!\n");
}
struct sockaddr_in src_addr = {0}; //用来存放对方(信息的发送方)的IP地址信息
int len = sizeof(src_addr); //地址信息的大小
char buf[1024] = {0};//消息缓冲区
//循环接受客户端发送过来的数据
while(1)
{
ret = recvfrom(udp_socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&src_addr, &len);
if(ret == -1)
{
break;
}
printf("[%s:%d]",inet_ntoa(src_addr.sin_addr),ntohs(src_addr.sin_port));//打印消息发送方的ip与端口号
printf("buf=%s\n",buf);
if(strcmp(buf, "exit") == 0)
{
break;
}
memset(buf, 0, sizeof(buf));//清空存留消息
}
上一篇: 【Linux网络编程】基于UDP的客户端/服务器程序
下一篇: 激光切割自动排版排料软件