Comparing a peer IPv6 address with a local host

I called getpeername on my connected socket and now I have the IPv6 address of the connected peer. How to determine if my IP address is localhost?

Edit: To clarify, I mean specifically localhost , as in the loopback IP address.

+4
source share
3 answers

I assume this is how to determine if the incoming connection is localhost if you have a peer connection in struct sockaddr_in6 obtained from getpeername , for example:

  struct sockaddr_in6 peer; socklen_t len = sizeof(peer); getpeername( sock, (struct sockaddr *) &peer, &len); // todo: error check 

From there, you can add your own struct sockaddr_in6 with the address localhost ::1 and compare the memory for equality:

  struct sockaddr_in6 localhost; memset(localhost.sin6_addr.s6_addr, 0, 16); localhost.sin6_addr.s6_addr[15] = 1; if( memcmp(peer.sin6_addr.s6_addr, localhost.sin6_addr.s6_addr, 16) == 0) printf("localhost!\n"); 

Or you can create an array of bytes that matches the localhost address:

  static const unsigned char localhost_bytes[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; if( memcmp(peer.sin6_addr.s6_addr, localhost_bytes, 16) == 0) printf("localhost!\n"); 

And watch out for the displayed local IPv4 host, ::ffff:127.0.0.1 . You may also need to check this out.

  static const unsigned char mapped_ipv4_localhost[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1 }; if( memcmp(peer.sin6_addr.s6_addr, mapped_ipv4_localhost, 16) == 0) printf("mapped IPv4 localhost!\n"); 
+3
source

In IPv6, the feedback address is ::1 .

At the binary level, 127 0, followed by a single 1.

+3
source

After you delete the loopback address, return the list of local computers with the current active IP addresses (the computer may have several IP addresses assigned to it for different networks), and then scroll through this list until you find a match. How you actually get this list depends on the OS you are using. The OS may have its own APIs for this (for example, Windows has GetAdaptersInfo () and related functions), or you can try using gethostname () with gethostbyname () or getaddrinfo ().

+3
source

Source: https://habr.com/ru/post/1310185/


All Articles