网络编程常用函数

网络编程常用函数

Created
Oct 21, 2021 08:13 AM
Tags
Linux
C/C++
Category
Coding
Last Edited
Last updated July 15, 2022
Abstract
Related to Reading List (Column)

一、Linux 协议栈

1. IP 地址转换

  • 将IP地址从点数格式转换成无符号长整型
    • struct sockaddr_in ina; ina.sin_addr.s_addr = inet_addr("132.241.5.10");
  • 将无符号长整型转换为点数格式
    • a1 = inet_ntoa(ina1.sin_addr); /* 这是198.92.129.1 */ a2 = inet_ntoa(ina2.sin_addr); /* 这是132.241.5.10 */ printf("address 1: %s ",a1); printf("address 2: %s ",a2); // 输出如下: // address 1: 132.241.5.10 // address 2: 132.241.5.10

2. 字节顺序

  • 将主机顺序转换为网络字节顺序
    • htons() htonl()
  • 将网络字节顺序转换为主机顺序
    • ntohs() ntohl()

      二、DPDK

      1. 程序初始化

      /* Check that there is an even number of ports to send/receive on. */ // 获取有效网卡的个数 nb_ports = rte_eth_dev_count_avail(); if (nb_ports < 2 || (nb_ports & 1)) rte_exit(EXIT_FAILURE, "Error: number of ports must be even\n");

      2. 端口初始化

      struct rte_eth_conf port_conf = { .rxmode = { .split_hdr_size = 0, }, .txmode = { .offloads = DEV_TX_OFFLOAD_VLAN_INSERT | DEV_TX_OFFLOAD_IPV4_CKSUM | DEV_TX_OFFLOAD_UDP_CKSUM | DEV_TX_OFFLOAD_TCP_CKSUM | DEV_TX_OFFLOAD_SCTP_CKSUM | DEV_TX_OFFLOAD_TCP_TSO, }, }; struct rte_eth_txconf txq_conf; struct rte_eth_rxconf rxq_conf; struct rte_eth_dev_info dev_info; ret = rte_eth_dev_info_get(port_id, &dev_info); if (ret != 0) rte_exit(EXIT_FAILURE, "Error during getting device (port %u) info: %s\n", port_id, strerror(-ret)); port_conf.txmode.offloads &= dev_info.tx_offload_capa; printf(":: initializing port: %d\n", port_id); ret = rte_eth_dev_configure(port_id, nr_queues, nr_queues, &port_conf); if (ret < 0) { rte_exit(EXIT_FAILURE, ":: cannot configure device: err=%d, port=%u\n", ret, port_id); } rxq_conf = dev_info.default_rxconf; rxq_conf.offloads = port_conf.rxmode.offloads;