Obtener el nombre de PC

(1/1)

.:WindHack:.:
Ya había programado esta función en Delphi, así que me decidí a traducirla a C/C++.

Código
/* DaW - Labs - http://daw-labs.com */
 
#include <windows.h>
 
int main(int argc, CHAR* argv[])
{
char Buffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD nSize = sizeof(Buffer);
if (GetComputerName(Buffer,&nSize))
{
MessageBox(0,Buffer,"Nombre de PC",MB_OK | MB_ICONINFORMATION);
}
return 0;

Foxy Rider:
Yo lo haría así, me parece más correcto (aún así siendo una forma vaga de escribirlo) ...
La forma Windows y forma POSIX

Código
#include <stdio.h>
#include <stdlib.h>
 
#ifdef _WIN32
#   include <windows.h>
#   define MAX_HOSTNAME_LEN MAX_COMPUTERNAME_LENGTH
#   define mGetComputerName(x,y) !GetComputerNameExA(ComputerNameDnsHostname,x,y)
#else
#   include <unistd.h>
   /* Nos guiamos por lo que define el estandar POSIX, otros sistemas Unix/Unix-Like usan HOST_NAME_MAX */
#   define MAX_HOSTNAME_LEN 255
#   define mGetComputerName(x,y) gethostname(x,y)
#endif
 
 
char* getComputerName()
{
   char* mName = (char*) malloc(MAX_HOSTNAME_LEN +1);
   if (mGetComputerName(mName,MAX_HOSTNAME_LEN) != 0)
   {
       free(mName);
       mName = 0;
   }
   return mName;
}
 
 
int main()
{
   printf("Hostname : %s",getComputerName());
   return 0;
}
 
 

y si estamos en más exigentes y en modo de "Pokemon exception handling" (For when you just gotta catch ’em all!), podés verificar el malloc() .... además agregar correspondiente free()

Saludos.

Edit: me olvidé de mencionar el free() xP

Navegación

[0] Índice de Mensajes