linux - 将端口号转换为字符串

标签 linux network-programming

我正在尝试将整数形式的端口号转换为字符串,以传递给 getaddrinfo() 调用。我的代码看起来像这样:

#define PORT_SIZE 5

void convert(int port) {
   char service[PORT_SIZE+1];
....
....
    memset(service, '\0', PORT_SIZE+1);
    snprintf(service, PORT_SIZE+1, "%d", port);
...
...
}

由于 linux 机器上的最大端口大小是 65535,因此将数组大小设置为五个字节来存储端口号是否正确?

谢谢!

最佳答案

没关系,如果生成的字符串长于PORT_SIZE 个字符,剩余的字符将被丢弃而不存储,只是计入函数返回的值,因此不会发生缓冲区溢出。并且在写入内容后会自动附加一个终止空字符,因此 memset() 是多余的。
或者直接调用 itoa (port, buffer, 10)

关于linux - 将端口号转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22658676/

相关文章:

haskell - Haskell 中是否有成熟的用于网络数据包处理的库?

android - 如何检测系统是否连接到 ad hoc 或基础设施 wifi?

c - `(void) inotify_rm_watch(fd, wd)` 和 `inotify_rm_watch(fd, wd)` 之间的区别

linux - bash 使用 "find"命令并删除用户的模式(使用特殊参数)

linux - 无法在 Oracle Linux (RedHat) 上安装 Apache

linux - 如何在 windows 中使用 timeval 等 Linux 库

c++ - boost::iostreams::mapped_file_sink 抛出未知异常

c - 关于 C 程序中 TCP 和 UDP 连接的问题

android - 在android中将静态ip设置为以太网

ubuntu - 如何禁用 Docker 内的所有网络连接?