查看: 28|回覆: 0

socket 编程获取本机及域名ip地址

[複製鏈接]

1

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2008-12-24
發表於 2019-9-11 16:03:00 | 顯示全部樓層 |閲讀模式

socket 编程获取本机及域名ip地址

#include <stdio.h>
#include <winsock2.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int ip(char name[],int a)
{
	int iResult;
	WSADATA wsaData;
	WORD v=MAKEWORD(2,2);
	iResult=WSAStartup(v,&wsaData);
	if(iResult!=0)
	{
		printf("WSAStartup failed: %d\n",iResult);
		return -1;
	}     //套接字初始化 
	
	int i=0;
	if(a==1)
		{
			printf("本机ip\n");
			gethostname(name,sizeof(name));
		}
//	printf("主机名:%s\n\n",name);//获取主机名 
	
	struct hostent *host=gethostbyname(name);
	for(i=0;host!=NULL&&host->h_addr_list!=NULL;i++)
	{
		char *p=inet_ntoa(*(struct in_addr *)host->h_addr_list);
		printf("h_name:%s\n",host->h_name);
		printf("IP Address #[%d]:%s\n",i+1,p);  //获取全部ip 
		
	}
	iResult=WSACleanup();
	if(iResult!=0)
	{
		printf("WSACleanup failed: %d\n",iResult);
		return -1;
	}     //套接字释放
}

int main()
{
	char namehost[200];
	int i;
	ip("",1);
	printf("\n请输入域名:");
	scanf("%s",namehost);
		ip(namehost,2);
	return 0;
}
/*int main(int argc, char *argv[]) {
	return 0;
}*/


来源:https://www.cnblogs.com/juicef/p/11506820.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部