UDP网络编程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP网络编程相关的知识,希望对你有一定的参考价值。
发送端程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
#define _WINSOCK_DEPRECATED_NO_WARNINGS //为了取消inet_addr警告 #include <WinSock2.h> #include <iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") #define IP "127.0.0.1"//自身的IP地址 #define PORT 8881 //自身的端口号 int main() { WSADATA wd; WSAStartup(0x0202, &wd); //2.2版本,启动网络socket //创建soket SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); if (INVALID_SOCKET == sock) { cout << "创建socket套接字(句柄)时出错:" << WSAGetLastError() << endl; return -1; } //创建头 sockaddr_in sa; //16字节也可以用sockaddr,但是需要设置太多的数据 sa.sin_family = 2; // family AF_INET sa.sin_port = htons(PORT); //将存储字节序转为网络字节序,高低字节变换,port = 0代表自动配送端口 //sa.sin_addr.S_un.S_addr = 0;//绑定本机所有IP, sa.sin_addr.S_un.S_addr = inet_addr(IP); //绑定 int n = bind(sock, (sockaddr*)&sa, sizeof (sa)); //需要强制转换为sockaddr*格式 if (SOCKET_ERROR == n) { cout << "绑定套接字时出错:" << WSAGetLastError() << endl; return -1; } sockaddr_in to; to.sin_family = 2; to.sin_port = htons(8883); //将存储字节序转为网络字节序 char s[256]; to.sin_addr.S_un.S_addr = inet_addr(IP); while ( true ) { //sa.sin_addr.S_un.S_addr = 0;//绑定本机所有IP, gets_s(s); sendto(sock, s, strlen (s), 0, (sockaddr*)&to, sizeof (to)); } } |
接收端程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
#define _WINSOCK_DEPRECATED_NO_WARNINGS //inet_addr #include <WinSock2.h> #include <iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") #define IP "192.168.1.107" #define PORT 8883 int main() { WSADATA wd; WSAStartup(0x0202, &wd); //2.2版本 //创建soket SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); if (INVALID_SOCKET == sock) { cout << "创建socket套接字(句柄)时出错:" << WSAGetLastError() <<endl; return -1; } sockaddr_in sa; sa.sin_family = 2; sa.sin_port = htons(PORT); //将存储字节序转为网络字节序 //sa.sin_addr.S_un.S_addr = 0;//绑定本机所有IP, sa.sin_addr.S_un.S_addr = inet_addr(IP); int n = bind(sock, (sockaddr*)&sa, sizeof (sa)); if (SOCKET_ERROR == n) { cout << "绑定套接字时出错:" << WSAGetLastError() << endl; return -1; } char s[4096] = {0}; while ( true ) { n = recv(sock, s, sizeof (s), 0); cout << "收到数据:" ; if (SOCKET_ERROR == n) { cout << "recv接收数据失败:" << WSAGetLastError() << endl; return -1; } s[n] = 0; cout << s << endl; } } |
以上是关于UDP网络编程的主要内容,如果未能解决你的问题,请参考以下文章