[ PHP ] Convert IPv6 address to IPv4

Function

I recieve IP address of user from node.js in IPv6 format and want to get IPv4 addresses in IPv4 format.

function get_simple_ip($ip)
	{
		$exploded_ip = explode(":", $ip);
		$size = sizeof($exploded_ip);
		
		if($size == 1) // ipv4 format
			return $ip;
			
		if($size == 4) // ipv4 in ipv6 format
		{
			if(empty($exploded_ip[0]) && empty($exploded_ip[1]) && strtoupper($exploded_ip[2]) == "FFFF")
				return $exploded_ip[3];
		}
		
        return $ip;  // default ipv6
	}

This function only for my situation, in yours it can be some different.

Example

31.95.64.173 -> 31.95.64.173

::ffff:31.95.64.173 -> 31.95.64.173

::ffff:31.95.64.173 -> 31.95.64.173

::FFFF:31.95.64.173 -> 31.95.64.173

21DA:7654:DE12:2F3B:02AA:EF98:FE28:9C5A -> 21DA:7654:DE12:2F3B:02AA:EF98:FE28:9C5A

 

If you know better solution, please, share in comments.

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *