ssize_t sendto(int sock, void *buf, size_t nbytes, int flags, struct sockaddr *to, socklen_t addrlen); //Linux int sendto(SOCKET sock, const char *buf, int nbytes, int flags, const struct sockadr *to, int addrlen); //WindowsLinux 和 Windows 下的 sendto() 函数类似,下面是详细参数说明:
ssize_t recvfrom(int sock, void *buf, size_t nbytes, int flags, struct sockadr *from, socklen_t *addrlen); //Linux int recvfrom(SOCKET sock, char *buf, int nbytes, int flags, const struct sockaddr *from, int *addrlen); //Windows由于 UDP 数据的发送端不定,所以 recvfrom() 函数定义为可接收发送端信息的形式,具体参数如下:
#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll #define BUF_SIZE 100 int main(){ WSADATA wsaData; WSAStartup( MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); //绑定套接字 struct sockaddr_in servAddr; memset(&servAddr, 0, sizeof(servAddr)); //每个字节都用0填充 servAddr.sin_family = PF_INET; //使用IPv4地址 servAddr.sin_addr.s_addr = htonl(INADDR_ANY); //自动获取IP地址 servAddr.sin_port = htons(1234); //端口 bind(sock, (SOCKADDR*)&servAddr, sizeof(SOCKADDR)); //接收客户端请求 SOCKADDR clntAddr; //客户端地址信息 int nSize = sizeof(SOCKADDR); char buffer[BUF_SIZE]; //缓冲区 while(1){ int strLen = recvfrom(sock, buffer, BUF_SIZE, 0, &clntAddr, &nSize); sendto(sock, buffer, strLen, 0, &clntAddr, nSize); } closesocket(sock); WSACleanup(); return 0; }代码说明:
htonl(INADDR_ANY)
来自动获取 IP 地址。#include <stdio.h> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll #define BUF_SIZE 100 int main(){ //初始化DLL WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0); //服务器地址信息 struct 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_port = htons(1234); //不断获取用户输入并发送给服务器,然后接受服务器数据 struct sockaddr fromAddr; int addrLen = sizeof(fromAddr); while(1){ char buffer[BUF_SIZE] = {0}; printf("Input a string: "); gets(buffer); sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr*)&servAddr, sizeof(servAddr)); int strLen = recvfrom(sock, buffer, BUF_SIZE, 0, &fromAddr, &addrLen); buffer[strLen] = 0; printf("Message form server: %s\n", buffer); } closesocket(sock); WSACleanup(); return 0; }先运行 server,再运行 client,client 输出结果为:
Input a string: C语言中文网
Message form server: C语言中文网
Input a string: task.lmcjl.com Founded in 2012
Message form server: task.lmcjl.com Founded in 2012
Input a string:
本文链接:http://task.lmcjl.com/news/17922.html