Support for IPv4 in IPv6

Backwards compatibility can mean make or break for a new technology. One reason why AMD has been successful with it’s 64bit chips is that they can run the vast body of 32bit application without a recompile. If IPv6 is to be as successful, it has to be similarly successful in interoperating with IPv4.

The Linux implementation of the IPv6 server socket API handles connections from IPv4 clients with the same code as it handles IPv6 client connections. I’ve taken and rewritten it to work with IPv6. Commented out lines show the original code. Just about every line I added has the number 6 in it somewhere.

#include
#include
#include
#include
#include
#include
#include

#define PORT 0x1234
#define DIRSIZE 8192

main()
{
char dir[DIRSIZE]; /* used for incomming dir name, and
outgoing data */
int sd, sd_current, cc, fromlen, tolen;
int addrlen;
// struct sockaddr_in sin;
// struct sockaddr_in pin;
struct sockaddr_in6 sin;
struct sockaddr_in6 pin;

/* get an internet domain socket */
// if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
if ((sd = socket(AF_INET6, SOCK_STREAM, 0)) == -1) {
perror(“socket”);
exit(1);
}

/* complete the socket structure */
memset(&sin, 0, sizeof(sin));
// sin.sin_family = AF_INET;
sin.sin6_family = AF_INET6;
// sin.sin_addr.s_addr = INADDR_ANY;
sin.sin6_addr = in6addr_any;
// sin.sin_port = htons(PORT);
sin.sin6_port = htons(PORT);

/* bind the socket to the port number */
if (bind(sd, (struct sockaddr *) &sin, sizeof(sin)) == -1) {
perror(“bind”);
exit(1);
}

/* show that we are willing to listen */
if (listen(sd, 5) == -1) {
perror(“listen”);
exit(1);
}
/* wait for a client to talk to us */
addrlen = sizeof(pin);
if ((sd_current = accept(sd, (struct sockaddr *) &pin, &addrlen)) == -1) {
perror(“accept”);
exit(1);
}
/* if you want to see the ip address and port of the client, uncomment the
next two lines */

/*
printf(“Hi there, from %s#\n”,inet_ntoa(pin.sin_addr));
printf(“Coming from port %d\n”,ntohs(pin.sin_port));
*/

char src_addr_str[INET6_ADDRSTRLEN];

if (inet_ntop(AF_INET6, &pin.sin6_addr,
src_addr_str,INET6_ADDRSTRLEN)){
printf(“Hi there, from  %s#\n”, src_addr_str);
printf(“Coming from port %d\n”,ntohs(pin.sin6_port));
}
/* get a message from the client */
if (recv(sd_current, dir, sizeof(dir), 0) == -1) {
perror(“recv”);
exit(1);
}

/* get the directory contents */

/* read_dir(dir); */

strcat (dir,” DUDE”);

/* acknowledge the message, reply w/ the file names */
if (send(sd_current, dir, strlen(dir), 0) == -1) {
perror(“send”);
exit(1);
}

/* close up both sockets */
close(sd_current); close(sd);

/* give client a chance to properly shutdown */
sleep(1);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.