Difference between revisions of "Socket functions"

From Ilianko
Line 18: Line 18:
 
inet_pton(AF_INET6, "2001:db8:63b3:1::3490", &(sa6.sin6_addr)); // IPv6
 
inet_pton(AF_INET6, "2001:db8:63b3:1::3490", &(sa6.sin6_addr)); // IPv6
 
</pre></code>
 
</pre></code>
 +
 +
// IPv4:
 +
char ip4[INET_ADDRSTRLEN];
 +
struct sockaddr_in sa;
 +
// space to hold the IPv4 string
 +
// pretend this is loaded with something
 +
inet_ntop(AF_INET, &(sa.sin_addr), ip4, INET_ADDRSTRLEN);
 +
printf("The IPv4 address is: %s\n", ip4);
 +
// IPv6:
 +
char ip6[INET6_ADDRSTRLEN]; // space to hold the IPv6 string
 +
struct sockaddr_in6 sa6;
 +
// pretend this is loaded with something
 +
inet_ntop(AF_INET6, &(sa6.sin6_addr), ip6, INET6_ADDRSTRLEN);
 +
printf("The address is: %s\n", ip6);

Revision as of 14:41, 12 April 2013


Byte Order Conversion

  • htons() host to network short
  • htonl() host to network long
  • ntohs() network to host short
  • ntohl() network to host long

IP address conversion

struct sockaddr_in sa; // IPv4
struct sockaddr_in6 sa6; // IPv6

inet_pton(AF_INET, "192.0.2.1", &(sa.sin_addr)); // IPv4
inet_pton(AF_INET6, "2001:db8:63b3:1::3490", &(sa6.sin6_addr)); // IPv6

// IPv4: char ip4[INET_ADDRSTRLEN]; struct sockaddr_in sa; // space to hold the IPv4 string // pretend this is loaded with something inet_ntop(AF_INET, &(sa.sin_addr), ip4, INET_ADDRSTRLEN); printf("The IPv4 address is: %s\n", ip4); // IPv6: char ip6[INET6_ADDRSTRLEN]; // space to hold the IPv6 string struct sockaddr_in6 sa6; // pretend this is loaded with something inet_ntop(AF_INET6, &(sa6.sin6_addr), ip6, INET6_ADDRSTRLEN); printf("The address is: %s\n", ip6);