关于socket编程中这个strncpy函数的一个问题
a question about this strncpy function in socket programming
我目前正在为我的带有 c 套接字的网络扫描器应用程序开发 portscanner。
我找到了这段代码,我想在这里了解 strncpy 的确切作用是什么!有人可以为我的网络编程初学者解释这段代码吗,谢谢 ..
嗯,它看起来像是将 sa 位设置为零。
大概相当于
memset(&sa, 0, sizeof sa);
或者,如果您的编译器允许,您可以使用
struct sockaddr_in sa = {.sin_family = AF_INET };
并摆脱
sa.sin_family = AF_INET;
strncpy((char*)&sa, "", sizeof sa);
这里作者试图将 0
设置为 sa
结构的每个字节。
根据strncpy
If the end of the source C string (which is signaled by a
null-character) is found before num characters have been copied,
destination is padded with zeros until a total of num characters have
been written to it.
如果我是你,我会这样做。
memset(&sa, 0 , sizeof sa);
strncpy((char*)&sa.sin_addr, (char*) host->h_addr, sizeof sa.sin_addr);
此处作者试图将保存第一个主机地址的 char *h_addr
复制到 s_addr
。
如果我是你,我会这样做。
sa.sin_addr.s_addr = inet_addr(host->h_addr);
我目前正在为我的带有 c 套接字的网络扫描器应用程序开发 portscanner。 我找到了这段代码,我想在这里了解 strncpy 的确切作用是什么!有人可以为我的网络编程初学者解释这段代码吗,谢谢 ..
嗯,它看起来像是将 sa 位设置为零。 大概相当于
memset(&sa, 0, sizeof sa);
或者,如果您的编译器允许,您可以使用
struct sockaddr_in sa = {.sin_family = AF_INET };
并摆脱
sa.sin_family = AF_INET;
strncpy((char*)&sa, "", sizeof sa);
这里作者试图将
0
设置为sa
结构的每个字节。根据strncpy
If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
如果我是你,我会这样做。
memset(&sa, 0 , sizeof sa);
strncpy((char*)&sa.sin_addr, (char*) host->h_addr, sizeof sa.sin_addr);
此处作者试图将保存第一个主机地址的
char *h_addr
复制到s_addr
。如果我是你,我会这样做。
sa.sin_addr.s_addr = inet_addr(host->h_addr);