使用Windows Socket API获取局域网的电脑IP和名字
最近一直在考虑如何通过socket遍历局域网的电脑,都没有比较好的方法,下面提供一种实现方法,速度慢了点,望高手指教。
#include <stdio.h>
#include <Winsock2.h>
void main(int argc, char* argv[])
{
// TODO: Add your control notification handler code here
//----------------------
// Declare and initialize variables
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return;
}
/* The WinSock DLL is acceptable. Proceed. */
char hostname[100];
int namelen = 100;
gethostname(hostname,namelen);
hostent* remoteHost;
char * addr;
remoteHost=gethostbyname(hostname);
addr = inet_ntoa(*(struct in_addr *)(remoteHost->h_addr));
int ip,iptmp[4];
iptmp[0] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b1;
iptmp[1] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b2;
iptmp[2] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b3;
iptmp[3] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b4;
ip = iptmp[0]<<24 | iptmp[1]<<16 | iptmp[2]<<8 | iptmp[3];
int i;
int len;
struct in_addr lan;
for(i = 1;i<255;i++)
{
ip = iptmp[0]<<24 | iptmp[1]<<16 | iptmp[2]<<8 | i;
char tmp[3];
sprintf(tmp,"%d",i);
printf(tmp);
printf("\t");
lan.S_un.S_addr = ntohl(ip);
addr = inet_ntoa(lan);
len = ntohl(ip);
remoteHost=gethostbyaddr((char *)&len,4,AF_INET);
if(NULL != remoteHost)
{
printf("%s\t%s",addr,remoteHost->h_name);
}
printf("\n");
}
WSACleanup();
return;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构