Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a peer's IPv6 address with localhost

Tags:

c

sockets

ipv6

I have called getpeername on my connected socket and now have an IPv6 address of the connected peer. How do I tell whether my peer's IP address is localhost?

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

like image 335
indiv Avatar asked Jan 23 '23 01:01

indiv


2 Answers

In IPv6, the loopback address is ::1.

At the binary level, that is 127 0's followed by a single 1.

like image 120
R Samuel Klatchko Avatar answered Feb 02 '23 15:02

R Samuel Klatchko


After ruling out the loopback address, retreive the local machine's list of current active IPs (the machine may have multiple IPs assigned to it for different networks) and then loop through that list until you find a match. How you actually get that list depends on the OS you are using. The OS may have its own APIs for that (Windows has GetAdaptersInfo() and related functions, for instance), or you can try using gethostname() with gethostbyname() or getaddrinfo().

like image 32
Remy Lebeau Avatar answered Feb 02 '23 15:02

Remy Lebeau