• Code-C++-Get local IP


    Code-C++-Get local IP

    September 30, 2020 1:17 PM

    使用Windows Socket API

    库:wsock32.lib
    头文件:

    • winsock.h
    • wsipx.h
    • wsnwlink.h
    • stdio.h

    涉及函数:

    • gethostname
    • gethostbyname
    • inet_ntoa
      涉及结构体:hostent

    Code:

    #pragma comment(lib, "wsock32.lib")
    
    #include <winsock.h>
    #include <wsipx.h>
    #include <wsnwlink.h>
    #include <stdio.h>
    
    int main()
    {
    	////////////////
    	// Initialize windows sockets API. Ask for version 1.1
    	//
    	WORD wVersionRequested = MAKEWORD(1, 1);
    	WSADATA wsaData;
    	if (WSAStartup(wVersionRequested, &wsaData)) {
    		printf("WSAStartup failed %s
    ", WSAGetLastError());
    		return -1;
    	}
    
    	//////////////////
    	// Get host name.
    	//
    	char hostname[256];
    	int res = gethostname(hostname, sizeof(hostname));
    	if (res != 0) {
    		printf("Error: %u
    ", WSAGetLastError());
    		return -1;
    	}
    	printf("hostname=%s
    ", hostname);
    
    	////////////////
    	// Get host info for hostname. 
    	//
    	hostent* pHostent = gethostbyname(hostname);
    	if (pHostent == NULL) {
    		printf("Error: %u
    ", WSAGetLastError());
    		return -1;
    	}
    
    	//////////////////
    	// Parse the hostent information returned
    	//
    	hostent& he = *pHostent;
    	printf("name=%s
    aliases=%s
    addrtype=%d
    length=%d
    ",
    		he.h_name, he.h_aliases, he.h_addrtype, he.h_length);
    
    	printf("name=%s
    aliases=%s
    addrtype=%d
    length=%d
    ",
    		pHostent->h_name, pHostent->h_aliases, pHostent->h_addrtype, pHostent->h_length);
    
    	sockaddr_in sa;
    	for (int nAdapter = 0; he.h_addr_list[nAdapter]; nAdapter++) {
    		memcpy(&sa.sin_addr.s_addr, he.h_addr_list[nAdapter], he.h_length);
    		// Output the machines IP Address.
    		printf("Address: %s
    ", inet_ntoa(sa.sin_addr)); // display as string
    	}
    
    	//////////////////
    	// Terminate windows sockets API
    	//
    	WSACleanup();
    
    	return 0;
    }
    
    
  • 相关阅读:
    八大算法手写
    Hql总结
    设计模式
    数据库连接失败(1)
    什么是ORM
    C++标准库之右值引用与交付语义
    C++标准库第二版笔记 2
    C++标准库第二版笔记 1
    Effective C++ 笔记:条款 32 确定你的public继承塑造出正确的is-a关系
    Effective C++ 笔记:条款 31 将编译关系降至最低
  • 原文地址:https://www.cnblogs.com/yongchao/p/13754073.html
Copyright © 2020-2023  润新知