Alexis Clarembeau
Alexis Clarembeau

Reputation: 2964

Go language use internal structures from C

I would like to be able, in Go, to translate one host address (let's use 'www.google.be') to a sockaddr structure and then use it from a C code.

Translating the host address to a sockaddr_any structure isn't too hard using the http://github.com/jbenet/go-sockaddr module. My code works and is the following:

ipAddr, _ := net.ResolveIPAddr("ip", "www.google.be")
sockAddr := sockaddrnet.IPAddrToSockaddr(ipAddr)
rawSockaddr, socklen, _ := sockaddr.SockaddrToAny(sockAddr)
cStruct := sockaddr.AnyToCAny(rawSockaddr)
C.printPointer(cStruct)

But, I'm not able to use this *sockaddr.C.struct_sockaddr_any variable: cStruct, from my C code (it has incomplete definition, so I can't use any of its fields), which is the following:

// #include <stdio.h>
// void printPointer(struct sockaddr_any *p){
//     printf(":: %p :: ", p); 
//     // How to use P as a sockaddr? 
// }
import "C"

sockaddr_any is defined in the core of the Go language (from https://golang.org/src/syscall/types_linux.go). So, I believe it should be linked by default with my C code. But, it seems not to be true. Does someone know what line could I use to include headers from the go language itself (here the syscall structures).

Thank you very much

Upvotes: 0

Views: 115

Answers (2)

Laszlo
Laszlo

Reputation: 801

You can use struct sockaddr*:

void printPointer(struct sockaddr_any *pp) {
    struct sockaddr *p = pp->addr;
    printf(":: %p :: ", p); 
}

since sockaddr_any is defined as:

struct sockaddr_any {
   struct sockaddr addr;
   char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
};

Upvotes: 1

Alexis Clarembeau
Alexis Clarembeau

Reputation: 2964

Using Laszlo answer, there is a simple solution for my problem. It isn't because the definition of the structure sockaddr_any isn't accessible in my context (there's no simple way to access the addr field) that we can't cast the pointer. So, I can simply do:

// #include <stdio.h>
// void printPointer(struct sockaddr_any *p){
//     struct sockaddr *usable_pointer = (struct sockaddr *) p; 
// }
import "C"

Then, I can use usable_pointer as any other sockaddr variable.

Thank you very much

Upvotes: 0

Related Questions