How do you change an IP address in C++? - c++

I need to do a number of network-related things in C++ that I would normally do with ifconfig in Linux, but I'd like to do it without parsing the output of a group of system calls. Which C or C++ libraries can I use to tell if a network adapter is up or down, read or change an adapter's IP address and netmask, and change the default DNS gateway?

Basically you need to make a bunch of ioctl calls using a socket handle (SIOCGIFADDR, SIOCADDRT). You can find sample programs that use it in the Linux kernel source under Documentation/networking. Some other links that might be helpful:
Network Interface operations on AIX
XBMC's implementation (check out CNetworkInterfaceLinux)
EDIT: Let me also add that if your target is desktop linux, then you can consider using the DBUS API to query network parameters using the NetworkManager.
http://people.redhat.com/dcbw/NetworkManager/NetworkManager DBUS API.txt (sorry there's some issue inserting links in edits)

You can always look at ifconfig's source code to see how they did it in the first place: http://archive.ubuntu.com/ubuntu/pool/main/n/net-tools/net-tools_1.60.orig.tar.gz

The NetworkManager service exposes an API over dbus for querying/manipulating the networking on many distributions these days. This may be too high-level for your purposes (e.g. you require finer control of the network, or dbus/NetworkManager are not available on the system...), but it may provide you with what you need.
Check out the dbus C++ bindings and the NetworkManager API (sorry, I can't find a better formatted version right now, but the information is there).

Related

Get the interface to be used by socket according to IP on Linux, with C/C++

According to this answer, the interface to be used by a socket will be selected automatically by the system if the destination address is specified when calling connect. What I am looking for is a simple way to know the name of that interface before calling connect with C or C++. I know this can be done with the command route get to $ADDR, but calling external command in program seems kinda dirty. Is there any way to do this in C/C++ other than parsing the route table or calling route?
You can open a netlink socket and query the routes then filter the one you need. Here is an article on Linux Journal that describes this method:
https://www.linuxjournal.com/article/7356
And here is an implementation in C of it:
https://gist.github.com/javiermon/6272065
It just needs a bit of adjustment for your needs.

which c/c++ library can be used for handling wifi connections for linux?

I want to implement WiFi manager program which should handle the following.
notification on wi-fi access point has come or gone
provide information of available wifi access point
connect/disconnect with a given wi-fi access point
Which is the recommended C/C++ WiFi library for Linux to achieve this?
On Fedora (at least), the preferred way to interact with NetworkManager is via DBus.
While wireless-tools and the like will work — even direct kernel calls, if you must — there are a couple of problems:
You'll probably need superuser privileges
NetworkManager will probably have a panic attack and get into fights with you, unless you stop its service
The user's normal networking controls (e.g. desktop tray icons) are almost certainly configured to use NetworkManager.
You can send and receive DBus messages for all the tasks you mentioned, for WiFi as well as arbitrary other types of network interfaces. The API is published here, for version 0.8.
For newer operating systems, there are apparently changes in the API, with a migration guide.
Their wiki should be really helpful.
I know both Fedora and Ubuntu use NetworkManager by default; I believe many other systems do, as well, but don't have an exhaustive list.
Of course, if you're using an embedded system, custom distribution, or something, then your mileage may vary.
That would be wireless-tools
I would recommend using directly the NetworkManager Library.
You can use low-level D-Bus library or libnm-glib library, that makes communication easier: example add connection glib
For more info, you can take a look into the code of the command line client nmcli.

Help me get started (traffic manipulation)

My main goal is to create an advanced program for manipulating the packets that route within my network via the router. Let my program have total control over the router. Set the download/upload speeds to my inputs, apply the effect to certain devices within in my network. Block upload or download traffic. Set second delay for either the upload or download speed. Specify % of loss packets, and the list goes on.
The problem is that I don't know where to start. I know most languages at the very most basic level. I'd like to create this program in either C, C++ or C# but I don't know yet. What else do I need to know before creating this program? Winsock or something? Winpcap APIs?
This goal is my motivation to learn programming to the extreme, and I'm really looking forward to it.
Thanks in advance!
Hmmm I guess you would want to look at pcap(?):
pcap
Check out:
http://beej.us/guide/bgnet/html/multi/index.html
'Beej's Guide to Network Programming
Using Internet Sockets'
All you could possibly need to know about programming sockets for capture and manipulation.
If I were you I'd write it in C, I'm writing a similar project at the moment in C++ and it's hell but too late to stop and start again.
Hope that helps.
Bear in mind that you either need a router that you can re-program or you need to use your PC as a router to do this.
Either way you want to look into how IPTABLES are implemented.
I've never seen Desktop Windows used as a router only Windows Server, though it may still be possible. libpcap is for packet capture, but not interception as I understand it. Programs like Wireshark use it to monitor copies of packets, but not to modify them. If you want to attempt this, my impression has been that there is a lot more documentation and tools for doing something like this with NetFilter/IPTables on Linux. You can even install something like OpenWRT on a compatible router and get a small, cheap Linux router, though having Desktop Linux will probably help for development. The NetFilter QUEUE library can be used with some IPTables firewall rules to redirects specific (or all) packets to a regular user program. That program can then read the packet and modify it or even request it to be dropped.
http://www.netfilter.org/projects/libnetfilter_queue/
If you want to manipulate network traffic on a Windows machine (as you mentioned), you will need some extra software. This operating system wont give you the full control over itself, which is fine for some reasons.
I think what you want to do, should be done with either winpcap or win10pcap if you are using Win10. These packages contains a windows driver and the libpcap user space library.

Writing a filter for incoming connections

I'm using C++/boost::asio under Win7.
I'm trying to "sniff" trafic over a given TCP/IP port. Hence, I'd like to listen on that port, receive messages, analyze them, but also immidately allow them to flow further, as if I never intercepted them. I want them to sink into the program that normally listens and connects on that port. Imagine a transparent proxy, but not for HTTP.
I'd rather find a code-based solution, but barring that, maybe you would suggest a tool?
what you are trying to do is basically a firewall program.
On windows there is several approach to do that, you can hook winsock. The better (or not hacky) is to use TDI filter (you take a look a this) or to make a NDIS filter.
Microsoft also introduced new API, WPF and LSP. I think you have better to use it because the TDI filter and NDIS wrapper involve driver programming which complicated and can be time consuming.
If this is for a product you are developing you may want to take a look at the WinPcap library http://www.winpcap.org/ which you can embed into your own program.
If you just need to analyze for yourself, use one of the tools that uses WinPcap, I have had great success with WireShark; but check out the WinPcap site for other tools
You cannot use boost::asio (or any other socket based library) for this as it consumes all the traffic.

Adding SSL support to existing TCP & UDP code?

Here's my question.
Right now I have a Linux server application (written using C++ - gcc) that communicates with a Windows C++ client application (Visual Studio 9, Qt 4.5.)
What is the very easiest way to add SSL support to both sides in order to secure the communication, without completely gutting the existing protocol?
It's a VOIP application that uses a combination of UDP and TCP to initially set up the connection and do port tunneling stuff, and then uses UDP for the streaming data.
I've had lots of problems in the past with creating the security certificates from scratch that were necessary to get this stuff working.
Existing working example code would be ideal.
Thank you!
SSL is very complex, so you're going to want to use a library.
There are several options, such as Keyczar, Botan, cryptlib, etc. Each and every one of those libraries (or the libraries suggested by others, such as Boost.Asio or OpenSSL) will have sample code for this.
Answering your second question (how to integrate a library into existing code without causing too much pain): it's going to depend on your current code. If you already have simple functions that call the Winsock or socket methods to send/receive ints, strings, etc. then you just need to rewrite the guts of those functions. And, of course, change the code that sets up the socket to begin with.
On the other hand, if you're calling the Winsock/socket functions directly then you'll probably want to write functions that have similar semantics but send the data encrypted, and replace your Winsock calls with those functions.
However, you may want to consider switching to something like Google Protocol Buffers or Apache Thrift (a.k.a. Facebook Thrift). Google's Protocol Buffers documentation says, "Prior to protocol buffers, there was a format for requests and responses that used hand marshalling/unmarshalling of requests and responses, and that supported a number of versions of the protocol. This resulted in some very ugly code. ..."
You're currently in the hand marshalling/unmarshalling phase. It can work, and in fact a project I work on does use this method. But it is a lot nicer to leave that to a library; especially a library that has already given some thought to updating the software in the future.
If you go this route you'll set up your network connections with an SSL library, and then you'll push your Thrift/Protocol Buffer data over those connections. That's it. It does involve extensive refactoring, but you'll end up with less code to maintain. When we introduced Protocol Buffers into the codebase of that project I mentioned, we were able to get rid of about 300 lines of marshalling/demarshalling code.
I recommend to use GnuTLS on both the client and the server side, only for the TCP connection. Forget about the UDP data for now. The GnuTLS documentation has example code for writing both clients and servers. Please understand that at least the server side (typically the TCP responder) needs to have a certificate; the client side can work with anonymous identification (although there is even an example without server certificate, using only DH key exchange - which would allow man-in-the-middle attacks).
In general, it is likely that you will have to understand the principles of SSL, no matter what library you use. Library alternatives are OpenSSL (both Unix and Windows), and SChannel (only Windows).
Have you tried the SSL support in Boost.Asio or ACE? Both use OpenSSL under-the-hood, and provide similar abstractions for TCP, UDP and SSL. Sample code is available in both the Boost.Asio and ACE distributions.
One thing you may need to keep in mind is that SSL is record-oriented instead of the stream-oriented (both TCP and UDP). This may affect how you multiplex events since you must, for example, read the full SSL record before you can call a read operation complete.
To help handle this with no changes to the application yo may want to look at the stunnel project (http://www.stunnel.org/). I don't think that it will handle the UDP for you though.
The yaSSL and CyaSSL embedded SSL/TLS libraries have worked well for me in the past. Being targeted at embedded systems, they are optimized for both speed and size. yaSSL is written in C++ and CyaSSL is written in C. In comparison, CyaSSL can be up to 20 times smaller than OpenSSL.
Both support the most current industry standards (up to TLS 1.2), offer some cool features such as stream ciphers, and are dual licensed under the GPLv2 and a commercial license (if you need commercial support).
They have an SSL tutorial which touches on adding CyaSSL into your pre-existing code as well: http://www.yassl.com/yaSSL/Docs-cyassl-manual-11-ssl-tutorial.html
Product Page: http://yassl.com/yaSSL/Products.html
Regards,
Chris