- 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); //Windows
- 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
- #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);
- //绑定套接字
- 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);
- //服务器地址信息
- 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);
- //不断获取用户输入并发送给服务器,然后接受服务器数据
- 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;
- }
Input a string: C语言中文网
Message form server: C语言中文网
Input a string: c.biancheng.net Founded in 2012
Message form server: c.biancheng.net Founded in 2012
Input a string:
联系客服