C++,在windows下获取本机ip地址
2个回答
展开全部
这样的代码很常见
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib");
int main()
{
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2, 2);
::WSAStartup(sockVersion, &wsaData);
char lv_name[50];
gethostname(lv_name, 50);
hostent * lv_pHostent;
lv_pHostent = (hostent *)malloc(sizeof(hostent));
if( NULL == (lv_pHostent = gethostbyname(lv_name)))
{
printf("get Hosrname Fail \n");
return 0;
}
SOCKADDR_IN lv_sa;
lv_sa.sin_family = AF_INET;
lv_sa.sin_port = htons(6000);
memcpy(&lv_sa.sin_addr.S_un.S_addr, lv_pHostent->h_addr_list[0], lv_pHostent->h_length);
printf("%s\n", inet_ntoa(lv_sa.sin_addr));
free(lv_pHostent);
return 0;
}
#include <WinSock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib");
int main()
{
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2, 2);
::WSAStartup(sockVersion, &wsaData);
char lv_name[50];
gethostname(lv_name, 50);
hostent * lv_pHostent;
lv_pHostent = (hostent *)malloc(sizeof(hostent));
if( NULL == (lv_pHostent = gethostbyname(lv_name)))
{
printf("get Hosrname Fail \n");
return 0;
}
SOCKADDR_IN lv_sa;
lv_sa.sin_family = AF_INET;
lv_sa.sin_port = htons(6000);
memcpy(&lv_sa.sin_addr.S_un.S_addr, lv_pHostent->h_addr_list[0], lv_pHostent->h_length);
printf("%s\n", inet_ntoa(lv_sa.sin_addr));
free(lv_pHostent);
return 0;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询