C/C++获取本机IP地址(转)

#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")

int doit(int, char **)
{
char host_name[255];
//获取本地主机名称
if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {
printf("Error %d when getting local host name.\n", WSAGetLastError());
return 1;
}
printf("Host name is: %s\n", host_name);

//从主机名数据库中得到对应的“主机”
struct hostent *phe = gethostbyname(host_name);
if (phe == 0) {
printf("Yow! Bad host lookup.");
return 1;
}

//循环得出本地机器所有IP地址
for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
printf("Address %d : %s\n" , i, inet_ntoa(addr));
}

return 0;
}

int main(int argc, char *argv[])
{
WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
return 255;
}

int retval = doit(argc, argv);

WSACleanup();

return retval;

}


http://hi.baidu.com/hcq11/item/29afbc9b741cc9d97a7f01ca

C++获取本机IP地址通常需要使用操作系统的特定API或相关库。在Windows系统中,你可以使用Winsock库中的`gethostbyname()`函数,而在类Unix系统中,可以使用C标准库的`gethostname()`和`gethostbyname()`函数来获取。以下是一个简单的例子,展示了如何在类Unix系统中获取本机IP地址: ```cpp #include <iostream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> std::string getLocalIPAddress() { std::string localIP; char hostname[NI_MAXHOST]; if (gethostname(hostname, sizeof hostname) != -1) { struct hostent *host = gethostbyname(hostname); if (host != nullptr) { for (int i = 0; host->h_addr_list[i] != nullptr; i++) { char ip_str[INET_ADDRSTRLEN]; inet_ntop(AF_INET, host->h_addr_list[i], ip_str, sizeof ip_str); localIP = ip_str; } } } return localIP; } int main() { std::string ip = getLocalIPAddress(); std::cout << "本机IP地址是: " << ip << std::endl; return 0; } ``` 这个程序首先通过`gethostname()`获取本机主机名,然后使用`gethostbyname()`根据主机获取主机信息,最后通过`inet_ntop()`函数将IP地址的网络字节序换为可读的字符串格式。 请注意,这个例子可能需要链接网络库,例如在gcc编译时使用`-lnsl`和`-lresolv`选项。 如果你使用的是Windows系统,那么可以通过Winsock API获取IP地址,但这通常需要初始化Winsock,创建一个套接字,然后使用相关函数来查询。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值