Du kannst die Funktion getaddrinfo verwenden, um die IP-Adresse eines Servers basierend auf dem Hostnamen zu erhalten.
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
const char *hostname = "example.com";
const char *port = "80"; // HTTP-Port
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
fprintf(stderr, "Failed to initialize Winsock\n");
return 1;
}
struct addrinfo hints, *res;
int sockfd;
ZeroMemory(&hints, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(hostname, port, &hints, &res) != 0) {
fprintf(stderr, "getaddrinfo failed\n");
WSACleanup();
return 1;
}
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd == INVALID_SOCKET) {
fprintf(stderr, "Error creating socket\n");
freeaddrinfo(res);
WSACleanup();
return 1;
}
if (connect(sockfd, res->ai_addr, (int)res->ai_addrlen) == SOCKET_ERROR) {
fprintf(stderr, "Error connecting to server\n");
closesocket(sockfd);
freeaddrinfo(res);
WSACleanup();
return 1;
}
const char *http_request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
send(sockfd, http_request, (int)strlen(http_request), 0);
char buffer[4096];
int bytes_received;
while ((bytes_received = recv(sockfd, buffer, sizeof(buffer) - 1, 0)) > 0) {
buffer[bytes_received] = '\0';
printf("%s", buffer);
}
if (bytes_received == SOCKET_ERROR) {
fprintf(stderr, "Error receiving data from server\n");
}
closesocket(sockfd);
freeaddrinfo(res);
WSACleanup();
return 0;
}