C - 使用 sin_addr 获取 IP 地址字符串

标签 c sockets ip

<分区>

我正在尝试从 struct in_addr 获取 IP 地址并将其放入 char 数组中。我尝试了以下代码,但遇到了段错误。

char ip[30];
strcpy(ip, (char*)inet_ntoa((struct in_addr)clt.sin_addr));

谁能告诉我如何解决这个问题?

最佳答案

稍微扩展你的代码以使其编译

#include <netinet/in.h>  
struct sockaddr_in clt;
int main() {
  char ip[30];
  strcpy(ip, (char*)inet_ntoa((struct in_addr)clt.sin_addr));
}

尝试在启用警告的情况下编译它(总是一个好主意)会给出一些警告,但肯定行不通

$ gcc -Wall -Wextra -O3 ntoa.c -o ntoa && ./ntoa
ntoa.c: In function 'main':
ntoa.c:5:3: warning: implicit declaration of function 'strcpy' [-Wimplicit-function-declaration]
ntoa.c:5:3: warning: incompatible implicit declaration of built-in function 'strcpy' [enabled by default]
ntoa.c:5:3: warning: implicit declaration of function 'inet_ntoa' [-Wimplicit-function-declaration]
ntoa.c:5:14: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
ntoa.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
Segmentation fault
$

在顶部包含缺少函数声明的 header (这也是一个好主意)

#include <arpa/inet.h>
#include <string.h>

显然修复了它:

$ gcc -Wall -Wextra -O3 ntoa.c -o ntoa && ./ntoa 
ntoa.c: In function 'main':
ntoa.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
$

关于C - 使用 sin_addr 获取 IP 地址字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31589654/

相关文章:

c - 虚拟地址系统上的进程地址空间

language-agnostic - 国际化:对于所有文化,IP 地址是否以相同的格式输入?

iphone - 将数据发送到 iPhone 上的套接字

linux - 如何获取重定向 UDP 消息的原始目标端口?

java - 如何从方法级别范围检索值?

python - 高效的ip查找

regex - 我需要使用 sed 转义哪些字符才能使此正则表达式正常工作

android - OPEN GL ES 和 EGL 库之间的混淆

c - 只有以 2 为底的对数时的自然对数实现

比较C中char数组的子范围