Home > Articles > Networking

  • Print
  • + Share This
From the author of

C Programming Changes

The C language has all the pieces you need to write socket-based programs in whatever network or protocol you want. You're only limited to network accessibility and operating system support. The basic system call to create an IPv4 socket looks like this:

int sd;
sd = socket(PF_INET, SOCK_STREAM, 0); /* Req. IPv4 protocol */

You use this call to start the process of connecting computers together across the network. PF_INET requests an IPv4 network, and the SOCK_STREAM requests a TCP connection. You might use this call for either the client or the server.

The IPv6 equivalent is very similar (note the changes in bold):

int sd;
sd = socket(PF_INET6, SOCK_STREAM, 0); /* Req. IPv6 protocol */

A server offers services through a published port. While setting up the port, the server program must convert the addresses into equivalent machine-readable format. Typically, you might use inet_ntoa() and inet_aton() to convert addressing from/to machine-readable form. For example, set up a sockaddr for binding an address to a published socket or connecting to a server:

struct sockaddr_in addr;
addr.sin_family = AF_INET;          /* request IPv4 */
inet_aton("16.32.64.127", &addr.sin_addr); /* Convert address */

Or you can get the address of the connecting client and print the results:

struct sockaddr_in addr;
int client, len=sizeof(addr);
client = accept(sd, &addr, &len);     /* Await connection */
printf("Connected: %s\n",
  inet_ntoa(addr.sin_addr));        /* print address */

The IPv6 equivalents are very close to these. Instead of using inet_ntoa() and inet_aton(), use inet_ntop() and inet_pton(), respectively. Using the previous examples, you can represent them in IPv6 like this:

struct sockaddr_in6 addr;
addr.sin_family = AF_INET6;          /* request IPv6 */
inet_pton(AF_INET6, "::FFFF:1020:40FF",   /* (hex of above) */
  &addr.sin6_addr);           /* Convert address */

Again, printing the client's IPv6 info, you use inet_ntop():

struct sockaddr_in6 addr;
int client, len=sizeof(addr);
client = accept(sd, &addr, &len);  /* Await IPv6 connection */
printf("Connected: %s\n",
  inet_ntop(AF_INET6, addr.sin6_addr));  /* print address */

These steps change the socket setup and client connection. From that point, if you've written your code carefully, you may not have to change anything. The operating system and network do the rest for you. You can delve into the extended socket options, though, which can increase your throughput tremendously.

  • + Share This
  • 🔖 Save To Your Account