C++获取本地ip、计算机名、判断端口是否被占用

Windows核心编程 专栏收录该内容
52 篇文章 0 订阅

1、获取ip地址、计算机名称和一个可用的端口号:

bool CConfig::GetIpAndPort()
{
	int nRet = 0, nNum = 0;

	if (!GetHostNameAndIP(m_szHostName, m_szIP))
		return false;

	while (1 != (nRet = PortIsValid(m_nPort)))
	{
		if (++nNum > 100)
			break;
		m_nPort++;
	}

	return nRet == 1 ? true : false;
}

相关调用函数实现:

获取ip和计算机名称:

bool CConfig::GetHostNameAndIP(char* pHostName, char* pHostIp, int nNameSize /*= MAX_PATH*/)
{
	if ((pHostName == nullptr) || (pHostIp == nullptr)){
		return false;
	}

	if (gethostname(pHostName, nNameSize) == SOCKET_ERROR)
	{
		return false;
	}

	struct hostent* pIpList = nullptr;
	if (nullptr == (pIpList = gethostbyname(pHostName)))
	{
		return false;
	}
	else
	{
		for (int i = 0; pIpList->h_addr_list[i] != 0; i++){

			struct in_addr in;
			memcpy(&in, pIpList->h_addr_list[i], sizeof(struct in_addr));

			int nIp1 = 0;
			sscanf(inet_ntoa(in), "%d.", &nIp1);
			if (192 == nIp1)
			{
				memcpy(pHostIp, inet_ntoa(in), strlen(inet_ntoa(in)));
				return true;
			}
		}
	}

	if (pIpList->h_addr_list[0] != 0)
	{
		struct in_addr in;
		memcpy(&in, pIpList->h_addr_list[0], sizeof(struct in_addr));
		memcpy(pHostIp, inet_ntoa(in), strlen(inet_ntoa(in)));
	}
	else
	{
		sprintf(pHostIp, "127.0.0.1");
	}

	return true;
}

判断端口号是否被占用:

/*
0 查询失败
1  端口没有被占用
2 端口被占用
*/
long CConfig::PortIsValid(ULONG nPort)
{
	int nRet = 0;
	DWORD dwSize = 0, dwRetVal = 0;
	PMIB_TCPTABLE pTcpTable = NULL;

	dwSize = sizeof(MIB_TCPTABLE);
	pTcpTable = (MIB_TCPTABLE *)malloc(sizeof(MIB_TCPTABLE));
	if (pTcpTable && ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == ERROR_INSUFFICIENT_BUFFER)) {
		free(pTcpTable), pTcpTable = NULL;
		pTcpTable = (MIB_TCPTABLE *)malloc(dwSize);
		if (pTcpTable == NULL) {
			printf("Error allocating memory\n");
			return nRet;
		}
	}

	do
	{
		if (NO_ERROR != (dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)))
		{
			break;
		}

		if (pTcpTable->dwNumEntries <= 0)
		{
			break;
		}

		for (DWORD i = 0; i < (int)pTcpTable->dwNumEntries; i++)
		{
			MIB_TCPROW TcpRow = pTcpTable->table[i];
			DWORD temp1 = TcpRow.dwLocalPort;
			int temp2 = temp1 / 256 + (temp1 % 256) * 256;
			if (temp2 == nPort)
			{
				nRet = 2;
				break;
			}
		}
		if (2 == nRet)
			break;

		nRet = 1;

	} while (0);

	if (pTcpTable) free(pTcpTable);
	return nRet;
}

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值