欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 网络编程 使用getaddrinfo的单纯UDP 通信

程序员文章站 2022-11-18 14:07:59
网络编程 使用getaddrinfo的单纯UDP 1,UDP发送端 2,UDP接收端 UDP发送端: c++ include include include include include include include include //getaddrinfo int main(int argc ......

网络编程 使用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]: %s\n", 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: %s\n", 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("%s\n", ipver);
  }

  n = sendto(sock, "bbbb\n", 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:%s\n", 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 failure\n");
  }
  printf("%s\n", buf);
  close(sock);
  return 0;
}

c/c++ 学习互助qq群:877684253

c/c++ 网络编程 使用getaddrinfo的单纯UDP 通信

本人微信:xiaoshitou5854