C代码在linux上运行良好,但在MacOS上运行不理想
这段代码在Linux上运行良好,但在终端中返回错误“gethostbyname:Undefined error:0”。我也尝试过网络上的其他代码,但它们要么在编译过程中返回一些错误,要么将IPv4地址显示为0.0.0.0。我能做些什么来让这一切顺利吗C代码在linux上运行良好,但在MacOS上运行不理想,c,macos,terminal,C,Macos,Terminal,这段代码在Linux上运行良好,但在终端中返回错误“gethostbyname:Undefined error:0”。我也尝试过网络上的其他代码,但它们要么在编译过程中返回一些错误,要么将IPv4地址显示为0.0.0.0。我能做些什么来让这一切顺利吗 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <netdb.h&g
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void checkHostName(int hostname)
{
if (hostname == -1) {
perror("gethostname");
exit(1);
}
}
void checkHostEntry(struct hostent* hostentry)
{
if (hostentry == NULL) {
perror("gethostbyname");
exit(1);
}
}
void checkIPbuffer(char* IPbuffer)
{
if (NULL == IPbuffer) {
perror("inet_ntoa");
exit(1);
}
}
int main()
{
char hostbuffer[256];
char* IPbuffer;
struct hostent* host_entry;
int hostname;
hostname = gethostname(hostbuffer, sizeof(hostbuffer));
checkHostName(hostname);
host_entry = gethostbyname(hostbuffer);
checkHostEntry(host_entry);
IPbuffer = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
printf("Hostname: %s\n", hostbuffer);
printf("Host IP: %s", IPbuffer);
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效检查主机名(int主机名)
{
如果(主机名==-1){
perror(“gethostname”);
出口(1);
}
}
无效检查hostentry(结构hostentry*hostentry)
{
如果(hostentry==NULL){
perror(“gethostbyname”);
出口(1);
}
}
void checkIPbuffer(char*IPbuffer)
{
if(NULL==IPbuffer){
佩罗尔(“内特乌恩托亚”);
出口(1);
}
}
int main()
{
字符主机缓冲区[256];
char*IPbuffer;
结构宿主*宿主项;
int主机名;
hostname=gethostname(hostbuffer,sizeof(hostbuffer));
检查主机名(hostname);
host_entry=gethostbyname(主机缓冲区);
检查主机输入(主机输入);
IPbuffer=inet_ntoa(*(地址中的结构)主机条目->地址列表[0]);
printf(“主机名:%s\n”,主机缓冲区);
printf(“主机IP:%s”,IPbuffer);
返回0;
}
您是否考虑过从代码中删除一些新行?注:在macos 10.15.5上,它工作正常gethostbyname()
没有设置errno
,因此将它与peror()
一起使用有点奇怪。建议:gethostbyname*()
和gethostbyaddr*()
函数已经过时。应用程序应该使用getaddrinfo(3)和getnameinfo(3)从@FredLarson那是gethostname
,问题是关于gethostbyname
@Barmar:啊,所讨论的代码同时使用了这两种方法。容易混淆。您是否考虑过从代码中删除一些新行?注:在macos 10.15.5上,它工作正常gethostbyname()
没有设置errno
,因此将它与peror()
一起使用有点奇怪。建议:gethostbyname*()
和gethostbyaddr*()
函数已经过时。应用程序应该使用getaddrinfo(3)和getnameinfo(3)从@FredLarson那是gethostname
,问题是关于gethostbyname
@Barmar:啊,所讨论的代码同时使用了这两种方法。他们很容易混淆。