网络编程 使用getaddrinfo的单纯udp
1,udp发送端
2,udp接收端
udp发送端:
#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 argc, char* argv[]){ int sock; addrinfo hints, *res; int err; int n; printf("argv[1]: %sn", argv[1]); if(argc !=2)return 1; //ip地址和网站都可以识别 memset(&hints, 0, sizeof(hints)); hints.ai_family = af_unspec;///ip地址和网站都可以识别 hints.ai_socktype = sock_dgram; err = getaddrinfo(argv[1], "12345", &hints, &res); if(err != 0){ printf("getaddrinfo: %sn", gai_strerror(err)); } sock = socket(res->ai_family, res->ai_socktype, 0); if(sock < 0){ perror("socket"); return 1; } { const char* ipver; switch(res->ai_family){ case af_inet: ipver = "ipv4"; case af_inet6: ipver = "ipv6"; default: ipver = "unknown"; } printf("%sn", ipver); } n = sendto(sock, "bbbbn", 5, 0, res->ai_addr, res->ai_addrlen); if(n < 0){ perror("sendto"); return 1; } close(sock); freeaddrinfo(res); return 0; }
发送端的执行方式:
./a.out 127.0.0.1
udp接收端
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <netdb.h> int main(){ int sock; addrinfo hints, *res; int err,n; char buf[2048]; memset(&hints, 0, sizeof(hints)); hints.ai_family = af_inet; hints.ai_socktype = sock_dgram; hints.ai_flags = ai_passive; err = getaddrinfo(null,"12345", &hints, &res); if(err != 0){ printf("getaddrinfo:%sn", gai_strerror(err)); return 1; } sock = socket(res->ai_family, res->ai_socktype, 0); if(sock < 0){ perror("socket"); return 1; } if(bind(sock, res->ai_addr, res->ai_addrlen) != 0){ perror("bind"); return 1; } freeaddrinfo(res); memset(buf, 0, sizeof(buf)); n = recv(sock, buf, sizeof(buf), 0); if(n < 0){ printf("recv failuren"); } printf("%sn", buf); close(sock); return 0; }
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607075.html