把内容过程中经常用的内容段记录起来,下面内容段是关于C++在windows下获取本地主机ipv4地址和ipv6地址的内容,应该是对码农有所用处。
#include <Winsock2.h>
#include <stdio.h>
#include
#include
#include<ws2tcpip.h>
using namespace std;
int get_ip()
{
struct addrinfo hint;
PHOSTENT hostinfo;
int ilRc;
gethostname(hostname, sizeof(hostname));
{
errno = GetLastError();
fprintf(stderr,"gethostbyname Error:%dn", errno);
return 1;
}
LPCSTR ip;
{
printf("ipv4 addr = %snn", ip);
hostinfo->h_addr_list++;
}
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if (ilRc < 0)
{
char str_error[100];
printf("str_error = %s", str_error);
return 0;
}
if(ailist == NULL)
{
printf("sorry not find the IP address,please try again n");
}
{
aip->ai_family == AF_INET6;
int i;
printf("ipv6 addr = ");
for(i = 0; i < 16; i++)
{
if(((i-1)%2) && (i>0))
{
printf(":");
}
printf("%02x",sinp6->sin6_addr.u.Byte[i]);
}
printf(" n");
printf(" n");
}
while(1);
}
int main(){
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
if ( err != 0 )
{
return 0;
}
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return 0;
}
get_ip();
return 0;
}