您的位置:首页 > 编程语言 > C语言/C++

获得本机ipv4和ipv6地址(即有线网卡地址)

2017-02-09 18:59 597 查看
程序源码如下:

1. 形参ipv4, ipv6为外部调用者传入,用来保存ipv4地址和ipv6地址,

2. MAX_PATH为自定义宏, 为数值260, IPVN_SIZE为数值50, DEFAULT_STR_PORT为字符串"8080"

3. 需在头文件中包含以下内容

#include <winsock2.h>

#include <ws2tcpip.h>

#pragma comment(lib,"Ws2_32.lib")

void CAllBox::getLocalIPv4( char * ip4)
{
// 获得本机主机名
#ifdef _WIN32
INT rc;
WSADATA wsaData;

rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (rc) {
return ;
}
#endif

char hostname[MAX_PATH];
memset(hostname, 0, MAX_PATH);
gethostname(hostname, MAX_PATH);
struct hostent FAR* lpHostEnt = gethostbyname(hostname);
if (lpHostEnt == NULL)
{
return;
}

// 取得IP地址列表中的第一个为返回的IP, 即有线网卡IP(因为一台主机可能会绑定多个IP)
LPSTR lpAddr = lpHostEnt->h_addr_list[0];

// 将IP地址转化成字符串形式
struct in_addr inAddr;
memmove(&inAddr, lpAddr, 4);

#ifdef _WIN32
WSACleanup();
#endif

strncpy(ip4, inet_ntoa(inAddr), strlen(inet_ntoa(inAddr)));

return;
}

void CAllBox::getLocalIPv6(char* ip6)
{
#ifdef _WIN32
INT rc;
WSADATA wsaData;

rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (rc) {
return ;
}
#endif

PHOSTENT hostinfo;
char hostname[HOSTNAME_LEN];      //主机名
char *port = DEFAULT_STR_PORT;			//端口号
int ilRc;
memset(hostname, 0, HOSTNAME_LEN);
gethostname(hostname, sizeof(hostname));

struct addrinfo hint;
struct addrinfo *ailist = NULL, *aip = NULL;
struct sockaddr_in6 *sinp6;

hint.ai_family = AF_INET6;          /*  hint 的限定设置  */
hint.ai_socktype = SOCK_STREAM;     /*   这里可是设置 socket type    比如  SOCK——DGRAM */
hint.ai_flags = AI_PASSIVE;         // flags 的标志很多  。常用的有AI_CANONNAME;
hint.ai_protocol = DEFAULT_PROT;               /*  设置协议  一般为0,默认 */
hint.ai_addrlen = DEFAULT_ADDRLEN;                /*  下面不可以设置,为0,或者为NULL  */
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
ilRc = getaddrinfo(hostname, port, &hint, &ailist);    /*通过主机名获得地址信息*/
if (ilRc < 0)
{
char str_error[ERR_MSG_LEN];
strcpy(str_error, (char *)gai_strerror(errno));
return ;
}
if (ailist == NULL)
{
return ;
}

aip = ailist;
aip->ai_family == AF_INET6;
sinp6 = (struct sockaddr_in6 *)aip->ai_addr;
inet_ntop(AF_INET6, (void*)&sinp6->sin6_addr, ip6, IPVN_SIZE);

#ifdef _WIN32
WSACleanup();
#endif

return ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ ipv4 网卡地址 ipv6