me icon indicating copy to clipboard operation
me copied to clipboard

学习 C/C++ (Part 23: UDP and SRT)

Open nonocast opened this issue 2 years ago • 0 comments

shell

tcp

  • server nc -l 3000
  • client nc localhost 3000

udp

  • server nc -u -l localhost 3000
  • client nc -u localhost 3000

lsof

  • lsof -i
  • lsof -i:3000
  • lsof -P -i:3000lsof -Pi:3000 不显示端口别名
  • lsof -P -iTCP:3000lsof -P -iUDP:3000
 ~ lsof -Pi:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71649 nonocast    3u  IPv4 0x5fc9824807db3e37      0t0  TCP *:3000 (LISTEN)
nc      71683 nonocast    3u  IPv4 0x5fc982433b42655f      0t0  UDP *:3000 
~ 
~ lsof -PiTCP:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71649 nonocast    3u  IPv4 0x5fc9824807db3e37      0t0  TCP *:3000 (LISTEN)
~ lsof -PiUDP:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71683 nonocast    3u  IPv4 0x5fc982433b42655f      0t0  UDP *:3000

UDP

server.c

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(void) {
  uint16_t port = 3000;
  struct sockaddr_in servaddr = {.sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY)};
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
  printf("udp server running ...\n");

  // recv
  uint8_t buffer[1024];
  struct sockaddr_in client;
  socklen_t clientlen = sizeof(client);

  while (true) {
    memset(buffer, 0x00, 1024);
    int n = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *) &client, &clientlen);
    struct hostent *clienthost =
        gethostbyaddr((const char *) &client.sin_addr.s_addr, sizeof(client.sin_addr.s_addr), AF_INET);
    char *clientaddr = inet_ntoa(client.sin_addr);
    printf("server received datagram from %s (%s)\n", clienthost->h_name, clientaddr);
    sendto(sockfd, buffer, n, 0, (struct sockaddr *) &client, clientlen);
  }

  return 0;
}
  • nc -u 0.0.0.0 3000nc -u 127.0.0.1 3000 (注: nc localhost不行)
  • nc -u 192.168.2.190 3000

随便发几条消息,程序输出如下:

make run
udp server running ...
server received datagram from localhost (127.0.0.1)
server received datagram from huis-mac-mini.lan (192.168.2.190)
server received datagram from huis-mac-mini.lan (192.168.2.190)
server received datagram from localhost (127.0.0.1)

udp和tcp的模型差别还是比较大的,udp在ip上的封装更少更直接,tcp额外增加了逻辑去除抖动和丢包,所以应该根据业务选择合适的模型。

SRT

// TODO:

参考阅读

nonocast avatar Jun 08 '22 09:06 nonocast