Friday, 13 September 2013

IPv4 mapped IPv6 addresses

IPv4 mapped IPv6 addresses

I'm trying to make a IP version-agnostic client/server. I've been playing
around with this in C++ and came up with something that works using the
IN6ADDR_SETV4MAPPED macro (as Microsoft so kindly recommends). I followed
the code sample here to accomplish this; my code that converts the address
is no different from the example and everything works. I can connect to
the server from the client by typing in both an IPv4 and IPv6 address
(application does the mapping accordingly).
Now I'm looking for a solution in C# to upgrade a simple chat server I
made and I've been unable to find any resources on how to use mapped
addresses. I haven't found a function that provides the equivalent of
IN6ADDR_SETV4MAPPED or any other facility in .net. My question is: how can
I go about using a IPv4-mapped IPv6 address in C# (client-side)?
What I've tried:
Prepend string "::ffff:" to dotted IPv4 notation, call Socket.Connect
using this address. Resulting address string looks like ::ffff:127.0.0.1.
Prepend string "::ffff:". Convert each octect from dotted format into hex
and separate with colons, call Socket.Connect. Resulting address string
looks like ::ffff:7f:0:0:1.
Neither of these approaches have worked so far.
Code snippet for server:
this.m_endPoint = new IPEndPoint(IPAddress.IPv6Any, 1337);
this.m_server.SetSocketOption(SocketOptionLevel.IPv6,
SocketOptionName.IPv6Only, 0);
this.m_server.Bind(this.m_endPoint);
this.m_server.Listen(10);
Code snippet for client:
public ClientNet(string host, short port)
{
IPAddress ip;
if(IPAddress.TryParse(host, out ip))
{
string[] octs = host.Split(new char[] { '.' });
host = "::ffff:";
for(int i = 0; i < octs.Length; ++i)
{
host += string.Format("{0:x}", int.Parse(octs[i]));
if(i + 1 != octs.Length)
{
host += ":";
}
}
}
else
{
throw new ClientCreateException("[in ClientNet.Constructor] Unable
to create client; use IPv4 address");
}
Socket client = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
client.Connect(host, port);
. . . //More initialization
}

No comments:

Post a Comment