C/C++使用Socket通信UDP

接收端

 1 #include <stdio.h>
 2 #include <WinSock2.h>
 3 
 4 #pragma comment(lib,"WS2_32.lib")
 5 
 6 int main(void)
 7 {
 8     WSADATA wsd;    // 初始化Socket的变量
 9     SOCKET s;        // 用于通信的Socket句柄
10     SOCKADDR_IN sRecvAddr,sSendAddr;    // 分别为接收地址和发送地址
11     USHORT uPort = 1401;                // 通信端口
12     CHAR szBuf[1024] = { 0 };            // 通信数据缓冲区
13     int nBufLen = 1024,nResult = 0, nSenderAddrSize = sizeof(sSendAddr);
14 
15     // 初始化Socket2.2版本
16     nResult = WSAStartup(MAKEWORD(2, 2), &wsd);
17     if (nResult != NO_ERROR)
18     {
19         printf("WSAStartup failed:%d\n", WSAGetLastError());
20         return 1;
21     }
22 
23     // 创建一个Socket,SOCK_DGRAM表示UDP类型
24     s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
25     if (s == INVALID_SOCKET)
26     {
27         printf("socket failed:%d\n", WSAGetLastError());
28         return 1;
29     }
30 
31     // 填充Socket接口
32     sRecvAddr.sin_family = AF_INET;        // 地址协议,AF_INET支持TCP和UDP
33     sRecvAddr.sin_port = htons(uPort);    // 通信端口,htons转为网络字节顺序
34     sRecvAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);    // 接收任意地址数据
35 
36     // 绑定Socket至本机
37     nResult = bind(s, (SOCKADDR *)&sRecvAddr, sizeof(sRecvAddr));
38     if (nResult != 0)
39     {
40         printf("bind failed:%d\n", WSAGetLastError());
41         return 1;
42     }
43 
44     printf("Waiting recv data...\n");
45     // 阻塞式接收数据
46     nResult = recvfrom(s, szBuf, nBufLen, 0, (SOCKADDR *)&sSendAddr, &nSenderAddrSize);
47     if (nResult == SOCKET_ERROR)
48     {
49         printf("recvfrom failed:%d\n", WSAGetLastError());
50     }
51     else{
52         printf("SenderIP  :%s\n", inet_ntoa(sSendAddr.sin_addr));
53         printf("SenderData:%s\n", szBuf);
54     }
55     // 关闭Socket连接
56     nResult = closesocket(s);
57     if (nResult == SOCKET_ERROR)
58     {
59         printf("closesocket failed:%d\n", WSAGetLastError());
60         return 1;
61     }
62     // 清理Socket
63     WSACleanup();
64 
65     system("pause");
66     return 0;
67 }

发送端

#include <stdio.h>
#include <WinSock2.h>
#include <Windows.h>

#pragma comment(lib,"WS2_32.lib")

int main(void)
{
    WSADATA wsd;
    SOCKET s;

    if (WSAStartup(MAKEWORD(2, 2), &wsd))
    {
        printf("WSAStartup failed!\n");
        return 1;
    }

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s == INVALID_SOCKET)
    {
        printf("socket failed,Error Code:%d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    SOCKADDR_IN addr;
    SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);

    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr = inet_addr("172.18.0.67");
    addr.sin_port = htons(1401);

    sendto(sockClient, "测试UDP通信!", 50, 0, (sockaddr *)&addr, 50);
    closesocket(s);
    WSACleanup();
    printf("Hello World!\n");
    system("pause");
    return 0;
}

效果图

posted @ 2018-09-18 16:44  BiaoGe  阅读(11241)  评论(0编辑  收藏  举报