Strumenti Utente

Strumenti Sito


programmazione:d:includere_codice_c

Includere codice C in applicazoini D

Autore: Fabio Di Matteo
Ultima revisione: 10/07/2025 11:25

Quello che ho fatto io in realtà è includere codice oggetto e richiamare una funzione C in D.

La funzione C

getip.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
 
/*Ritorna l'indirizzo locale usato per le connessioni all'esterno e  NULL se fallisce*/
 
char* GetLocalIp() 
{
	/*Modificare per cambiare DNS server*/
	unsigned short port = 53;
	const char* GoogleDnsIp = "8.8.8.8";
 
 
	/*Riempo le strutture dati per il server DNS*/
	int sd;
	struct sockaddr_in server;
	struct hostent *hp;
 
	hp = gethostbyname(GoogleDnsIp);
	bzero(&server, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr =((struct in_addr*)(hp->h_addr))->s_addr;
 
	/*Riempo le strutture dati per il client*/
	struct sockaddr_in client;
	struct hostent *cp;
 
	cp = gethostbyname("127.0.0.1");
	bzero(&client, sizeof(client));
	client.sin_family = AF_INET;
	client.sin_port = htons(port);
	client.sin_addr.s_addr =((struct in_addr*)(cp->h_addr))->s_addr;
 
 
	/* Creo il socket */
	if((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
    		printf("Errore nella creazione del socket!\n");
    		return NULL;
	}
 
 
	/* connettiamoci all'host */
	if (connect(sd, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
    	printf("Errore di connessione!\n");
		return NULL;
	}
 
	/*Individuo il mio indirizzo ip pubblico*/
	socklen_t* clientlen = (socklen_t* )sizeof(client);
	getsockname(sd, (struct sockaddr *) &client, (socklen_t*) &clientlen);	
 
	/*Lo converto in stringa e lo scrivo sulla variabile*/
	char* MyLocalAddress=malloc(sizeof(20));
	inet_ntop(AF_INET, &client.sin_addr.s_addr, MyLocalAddress, 20);
 
	/*Chiudiamo il socket*/
	close(sd);
 
	return MyLocalAddress;
}

L'applicazione principale in D

app.d

import std.stdio;
 
//prototipo funzione C
extern(C) {
    char* GetLocalIp();
}
 
 
void main()
{
	printf("My local ip: %s\n",GetLocalIp() );
}

makefile

all:
	gcc -c getip.c
	gdc app.d getip.o -o app

gcc -c getip.c crea il file getip.o che verrà incluso da gdc successivamente.

programmazione/d/includere_codice_c.txt · Ultima modifica: 10/07/2025 11:31 da Fabio Di Matteo