Please suggest how to get the IP address of my system (logical address) using C++ and Linux.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
“Logical Address” is not meaningful. You either want an interface address (the IP that hosts on the same local network as the machine see), or you want the publicly-facing Internet address (the IP address hosts will see when this machine connects to them). The IP addresses will only be the same if the machine is directly connected to the Internet, which often isn’t true.
Second, Linux hosts can (and do) have multiple interfaces, so which interface is just as important. It might be routing related (in which case it depends on the destination), or it might use policy routing (which again: will depend on the actual traffic).
Third: Linux hosts may have multiple addresses. That is, the system administrator may bind multiple IP addresses to the interface, either by using sub-interfaces (e.g.
ifconfig eth0:2 ...) or by simply adding the secondary addresses (e.g.ip addr add ip dev eth0).That’s why your best bet is to tell the user what you want to do, and ask the user to give you the right piece of information, or just try and make the connection, and rely on the system to do the Right Thing.
For the few cases where you actually need an IP address (for example, if you’re implementing an FTP client), a specialized approach will be the correct approach (in the FTP client case: using the results of
getsockname()on the control channel). Knowing exactly why you think you need the IP address (and what information you have) will help get you a better answer.