解析此字符串中的IPV4地址?

时间:2013-12-17 21:13:40

标签: c++

我使用的网络API为我提供了如下客户端IP:

[::ffff:127.0.0.1]:54222:54222

我需要能够检测到2个客户端是否正在尝试从同一IP地址进行连接。我不允许多于一个。为此,我需要解析此字符串的ipv4部分。

我只是不确定如何。

我不能只做一个简单的子串来获得它。

由于

编辑:我不能只使用整个字符串,因为每个客户端都是唯一的,而不是每个IP地址。

1 个答案:

答案 0 :(得分:1)

像...一样的东西。

/* parses 's' looking for a string between : and ] . If found, copies that
string into ipv4 and returns 1 */
int extract_ip4 (char *s, char *ipv4)
{
  char *p,*q;
  int i;

  q = strchr (s, ']');  /* search for ']' */
  if (!q)
    return 0;
  for (p=q;p!=s && *p!=':';p--);  /* search for ':' backwards from ']' */
  if (p==s)
    return 0;
  strncpy (ipv4,p+1,q-p-1);  /* copy portion of string to ipv4 */
  ipv4[q-p-1]='\0';
  return 1;             /* address found and copied */
}