linux平台获取ip地址
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main() {
char hostname[256];
char ip[INET6_ADDRSTRLEN];
/** 获取主机名 **/
if (gethostname(hostname, sizeof(hostname)) == -1) {
perror("Failed to get hostname");
return -1;
}
struct hostent *he;
struct in_addr **addr_list;
/** 获取主机信息 **/
if ((he = gethostbyname(hostname)) == NULL) {
herror("Failed to get host by name");
return -1;
}
addr_list = (struct in_addr **)he->h_addr_list;
/** 获取IP地址 **/
for (int i = 0; addr_list[i] != NULL; i++) {
strcpy(ip, inet_ntoa(*addr_list[i]));
printf("IP address: %s\n", ip);
}
return 0;
}
windows平台获取ip地址
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
fprintf(stderr, "Failed to initialize Winsock\n");
return -1;
}
char hostname[256];
char ip[INET6_ADDRSTRLEN];
/** 获取主机名 **/
if (gethostname(hostname, sizeof(hostname)) == -1) {
fprintf(stderr, "Failed to get hostname\n");
WSACleanup();
return -1;
}
struct hostent *he;
struct in_addr **addr_list;
/** 获取主机信息 **/
if ((he = gethostbyname(hostname)) == NULL) {
fprintf(stderr, "Failed to get host by name\n");
WSACleanup();
return -1;
}
addr_list = (struct in_addr **)he->h_addr_list;
/** 获取IP地址 **/
for (int i = 0; addr_list[i] != NULL; i++) {
strcpy(ip, inet_ntoa(*addr_list[i]));
printf("IP address: %s\n", ip);
}
WSACleanup();
return 0;
}
评论区