网络编程 udp 发送端 bind 作用
upd 发送端 调用bind函数的效果:把socket特定到一个指定的端口,如果不调用bind,内核会随机分配一个端口。
upd 发送端 调用bind函数的目的:假如有2个发送端,接收端需要识别是从哪个发送端过来的,就可以分别在发送端调用bind函数,这样一来,接收端就能够知道是哪个发送端过来的数据了。
运行方法:先运行【1,先接收再发送】,再运行【2,先发送再接收】
1,先接收再发送:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h>//getaddrinfo int main(){ int sock; sockaddr_in addr; sockaddr_in senderinfo; socklen_t addrlen; char buf[2048]; char senderstr[16]; int n; sock = socket(af_inet, sock_dgram, 0); addr.sin_family = af_inet; addr.sin_port = htons(12345); addr.sin_addr.s_addr = inaddr_any; bind(sock, (sockaddr*)&addr, sizeof(addr)); while(1){ memset(buf, 0, sizeof(buf)); addrlen = sizeof(senderinfo); n = recvfrom(sock, buf, sizeof(buf) - 1, 0, (sockaddr*)&senderinfo, &addrlen); inet_ntop(af_inet, &senderinfo.sin_addr, senderstr, sizeof(senderstr)); printf("recvfrom: %s, port=%dn", senderstr, ntohs(senderinfo.sin_port)); sendto(sock, buf, n, 0, (sockaddr*)&senderinfo, addrlen); printf("send data to: %s, port=%dn", senderstr, ntohs(senderinfo.sin_port)); } }
执行方式:
g++ -g udp_recv_send.cpp -std=c++11 -o se ./re
2,先发送再接收:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h>//getaddrinfo void print_port_num(int sock){ sockaddr_in s; socklen_t sz = sizeof(s); getsockname(sock, (sockaddr*)&s, &sz); printf("%dn", ntohs(s.sin_port)); } int main(int argc, char* argv[]){ int sock; sockaddr_in addr; sockaddr_in senderinfo; socklen_t senderinfolen; int n; char buf[2048]; sockaddr_in myname; if(argc != 2){ return 1; } sock = socket(af_inet, sock_dgram, 0); addr.sin_family = af_inet; addr.sin_port = htons(12345); inet_pton(af_inet, argv[1], &addr.sin_addr.s_addr); myname.sin_family = af_inet; myname.sin_addr.s_addr = inaddr_any; myname.sin_port = htons(34567); bind(sock, (sockaddr*)&myname, sizeof(myname)); n = sendto(sock, "hello", 5, 0, (sockaddr*)&addr, sizeof(addr)); if(n < 1){ perror("sendto"); return 1; } print_port_num(sock); memset(buf, 0, sizeof(buf)); senderinfolen = sizeof(senderinfo); recvfrom(sock, buf, sizeof(buf), 0, (sockaddr*)&senderinfo, &senderinfolen); printf("%sn", buf); close(sock); return 0; }
./a.out 127.0.0.1
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607071.html