网络编程 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=%d\n", senderstr, ntohs(senderinfo.sin_port));
sendto(sock, buf, n, 0, (sockaddr*)&senderinfo, addrlen);
printf("send data to: %s, port=%d\n", 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("%d\n", 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("%s\n", buf);
close(sock);
return 0;
}
./a.out 127.0.0.1
c/c++ 学习互助QQ群:877684253
本人微信:xiaoshitou5854
原文地址:https://www.cnblogs.com/xiaoshiwang/p/9775784.html
时间: 2024-10-12 18:35:46