0
votes

What I'm trying is that:

I have a struct:

typedef struct {
   unsigned int id;
   struct ??? addr;
} Peer;

I just want to have some methods like:

mypeer1.addr = storeAddr("192.168.1.1", 80);
mypeer2.addr = storeAddr("FE80:0000:0000:0000:0202:B3FF:FE1E:8329", 80);

and then

print("%s, %d", getAddrIp(mypeer1.addr.ip), getAddrIp(mypeer1.addr.ip));

I tried with sockaddr_storage and getaddrinfo and etc... but after 2 days of try and fail i need help.

a working example is very appreciate! thanks!

EDIT: clarification

1) I want a data structure that can hold a ipv4 OR a ipv6 address and a port (maybe sockaddr_storage?)

2) I want a method to store a new address (ipv4 OR ipv6 and port) in this structure, from a string

3) I want a method to print the ip address AND the port from this structure

EDIT2: my best attempt for now

typedef struct {
   unsigned int id;
   addrinfo* addr;
} Peer;

examplePeer1 = (Peer) { 0, NULL };
getaddrinfo("192.168.1.1", "80", NULL, &examplePeer1.addr);

but now i don't know how to print the ip and the port

1
What's your best attempt after two days? - Weather Vane
I added my best attempt! :) - Suxsem

1 Answers

1
votes

I finally did it!

typedef struct addrinfo Addrinfo;

typedef struct {
   unsigned int id;
   Addrinfo* addr;
} Peer;

void addr_log(Addrinfo* addr) {
   if (addr->ai_family == AF_INET6) {
      struct sockaddr_in6* saddr = (struct sockaddr_in6*)addr->ai_addr;
      char ip_s[INET6_ADDRSTRLEN];
      inet_ntop(AF_INET6, &(saddr->sin6_addr), ip_s, INET6_ADDRSTRLEN);
      printf("%s\n", ip_s);
      printf("%hu\n", ntohs(saddr->sin6_port));
   } else if (addr->ai_family == AF_INET) {
      struct sockaddr_in* saddr = (struct sockaddr_in*)addr->ai_addr;
      char ip_s[INET_ADDRSTRLEN];
      inet_ntop(AF_INET, &(saddr->sin_addr), ip_s, INET_ADDRSTRLEN);
      printf("%s\n", ip_s);
      printf("%hu\n", ntohs(saddr->sin_port));
   }
}

Peer examplePeer1;
Peer examplePeer2;

int main (int argc, char *argv[])
{
   examplePeer1 = (Peer) { 0, NULL };
   getaddrinfo("FE80:0000:0000:0000:0202:B3FF:FE1E:8329", "4444", NULL, &examplePeer1.addr);
   examplePeer2 = (Peer) { 0, NULL };
   getaddrinfo("192.168.1.1", "5555", NULL, &examplePeer2.addr);

   addr_log(examplePeer1.addr);
   addr_log(examplePeer2.addr);
}