c语言调用本机ip地址时如何定义gethostname函数
charFARname[MAX_HOSTNAME_LEN];iErrorCode=gethostname(name,MAX_HOSTNAME_LEN);CheckSock...
char FAR name[MAX_HOSTNAME_LEN]; iErrorCode = gethostname(name, MAX_HOSTNAME_LEN); CheckSockError(iErrorCode, "gethostname"); struct hostent FAR *pHostent; pHostent = (struct hostent *)malloc(sizeof(struct hostent)); pHostent = gethostname (name);
展开
2个回答
展开全部
//c++获取本机IP
#include <stdio.h>
#include <stdlib.h>
#include <WINSOCK2.H>
#pragma comment(lib,"ws2_32.lib")
int getIP(int ,char**)
{
char host_name[255];
if(gethostname(host_name,sizeof(host_name))==SOCKET_ERROR)
{
printf("Error %d when getting local host name\n",WSAGetLastError());
return -1;
}
printf("host name:%s\n",host_name);
struct hostent *phe=gethostbyname(host_name);
if(phe==0)
{
printf("Error host lookup\n");
return -1;
}
for(int i=0;phe->h_addr_list[i]!=0;++i)
{
struct in_addr addr;
memcpy(&addr,phe->h_addr_list[i],sizeof(struct in_addr));
printf("Address %d :%s\n",i,inet_ntoa(addr));
}
return 0;
}
int main(int argc,char *argv[])
{
WSAData wsaData;
if(WSAStartup(MAKEWORD(1,1),&wsaData)!=0)
{
system("pause");
return -1;
}
int result=getIP(argc,argv);
WSACleanup();
system("pause");
return result;
}
#include <stdio.h>
#include <stdlib.h>
#include <WINSOCK2.H>
#pragma comment(lib,"ws2_32.lib")
int getIP(int ,char**)
{
char host_name[255];
if(gethostname(host_name,sizeof(host_name))==SOCKET_ERROR)
{
printf("Error %d when getting local host name\n",WSAGetLastError());
return -1;
}
printf("host name:%s\n",host_name);
struct hostent *phe=gethostbyname(host_name);
if(phe==0)
{
printf("Error host lookup\n");
return -1;
}
for(int i=0;phe->h_addr_list[i]!=0;++i)
{
struct in_addr addr;
memcpy(&addr,phe->h_addr_list[i],sizeof(struct in_addr));
printf("Address %d :%s\n",i,inet_ntoa(addr));
}
return 0;
}
int main(int argc,char *argv[])
{
WSAData wsaData;
if(WSAStartup(MAKEWORD(1,1),&wsaData)!=0)
{
system("pause");
return -1;
}
int result=getIP(argc,argv);
WSACleanup();
system("pause");
return result;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
Storm代理
2023-07-25 广告
2023-07-25 广告
StormProxies是一家国内优质海外HTTP代理商,拥有一个庞大的IP资源池,覆盖200多个地区,IP数量大且匿名度高。其优点还包括超高并发、稳定高效、技术服务等特点,同时提供HTTP、HTTPS以及SOCKS5协议支持。此外,Sto...
点击进入详情页
本回答由Storm代理提供
展开全部
函数声明为
int PASCAL FAR gethostname(char FAR *name, int namelen);
所以 , 应该是
char name[65];
int ret = gethostname(name, sizeof(name));
if(ret == 0) printf("name is %s\n", name);
else printf("get failed ret=%d\n", ret);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询