티스토리 뷰
728x90
GetMyIPs C++ Code
This code retrieves the IP addresses of the system's network interfaces on both Windows and Linux platforms using C++14.
#include <iostream>
#include <vector>
#include <string>
// Platform-specific includes
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
std::vector<std::string> GetMyIPs() {
std::vector<std::string> ipAddresses;
#ifdef _WIN32
// Initialize Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed." << std::endl;
return ipAddresses;
}
char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
std::cerr << "gethostname failed." << std::endl;
WSACleanup();
return ipAddresses;
}
struct addrinfo hints = {};
hints.ai_family = AF_INET; // IPv4
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result = nullptr;
if (getaddrinfo(hostname, nullptr, &hints, &result) != 0) {
std::cerr << "getaddrinfo failed." << std::endl;
WSACleanup();
return ipAddresses;
}
for (struct addrinfo* ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
struct sockaddr_in* sockaddr_ipv4 = reinterpret_cast<struct sockaddr_in*>(ptr->ai_addr);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &sockaddr_ipv4->sin_addr, ip, sizeof(ip));
ipAddresses.emplace_back(ip);
}
freeaddrinfo(result);
WSACleanup();
#else
struct ifaddrs* ifaddr;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
return ipAddresses;
}
for (struct ifaddrs* ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr) continue;
if (ifa->ifa_addr->sa_family == AF_INET) { // IPv4 only
char ip[INET_ADDRSTRLEN];
struct sockaddr_in* sockaddr_ipv4 = reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr);
inet_ntop(AF_INET, &sockaddr_ipv4->sin_addr, ip, sizeof(ip));
ipAddresses.emplace_back(ip);
}
}
freeifaddrs(ifaddr);
#endif
return ipAddresses;
}
int main() {
auto ips = GetMyIPs();
std::cout << "IP Addresses:" << std::endl;
for (const auto& ip : ips) {
std::cout << " - " << ip << std::endl;
}
return 0;
}
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 서귀포
- PowerShell
- Build
- 서귀포블루버블
- Linux
- 외돌개
- C++
- 윈도우
- DLL
- 울릉도
- OpenSource
- 현포다이브
- 성산블루버블
- 티스토리챌린지
- 패턴
- 블루버블다이브팀
- CMake
- C#.NET
- 블루버블
- C#
- C# 고급 기술
- 블루버블다이빙팀
- script
- 제주도
- Windows
- ip
- 암호화
- 스쿠버다이빙
- C
- 스쿠버 다이빙
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
글 보관함
250x250