bind function of UDP sender in network programming
The effect of calling bind function on the sender of upd: assign socket to a specific port. If bind is not called, the kernel will randomly assign a port.
The purpose of the upd sender calling the bind function: if there are two senders and the receiver needs to identify which sender is coming from, it can call the bind function at the sender respectively, so that the receiver can know which sender is coming from.
Operation method: run [1, receive and then send], then run [2, send and then receive]
1. First receive and then send:
#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)); } }
Execution mode:
g++ -g udp_recv_send.cpp -std=c++11 -o se ./re
2. Send before receive:
#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