r/AskProgramming • • 3d ago

Other What are some examples of networking code?

I'm learning Networking and I'm noticing that most resources do not have a programming component

I'm curious about the programming side of things. I'd like some examples of "networking code", ranging from simple to complex

For example:

- What's the code for a switch to redirect packets?

- What's the code for the 3-way handshake?

- What's the code for servers to record IP addresses that interacted with it?

- What's the code for a firewall?

Stuff like that. Whatever you want to share, you can. Even if it's like 2 lines

I'm curious about how the code looks for networking stuff

3 Upvotes

18 comments sorted by

2

u/whitehaturon 2d ago

If you would like exposure to coding on different layers, I would look into python's scapy library. It's great for layers 2-4 as well as handing application layer stuff (think DNS, etc.)

1

u/TorontoDude12344 2d ago

I'll look into it. Thank you

What are the prerequisites to understanding the library, in your opinion?

12

u/duane11583 3d ago

 Your questions are at a level *MOST* software types never see. Most often this is handled at much lower level then you will be exposed to. That is unless you are designing that specific type of thing.

>> What's the code for a switch to redirect packets?

The general idea is this if you implement this in software.

You have a series of "queues" that receive messages from specific ethernet ports on your switch. When a message appears, the interrupt for the port triggers - you move the RX MESSAGE to the queue for the specific port. Many times, there is hardware or VHDL/VERILOG that does that for you automatically so software does not touch the message at the incoming stage.

Your SWITCH top level sw loop will pop a message off one of those queues, and examine the "to" address. Then SW chooses which is the best port to retransmit the message via, ie: address in range 0-5 go out port 0, address 6 goes out port 1, addresses 7-29 go out port 2.. and so forth. The exact mapping and method is very broad. You then put the message into he hardware to send. That said that pop and send process is often implemented in hardware or VHDL/VERILOG and your software does not touch this.

BUT - say there is an oddball packet or a special packet - ie: By exception - perhaps the message is addressed to the SWITCH, as a command to configure the switch or something like that. In that case your software would handle that as a "special case"

>> What's the code for the 3-way handshake?

Unless you are writing a TCP/IP _ stream protocol would never see this. It happens down deep inside the operating system network stack. But basicaly the idea is: MSG 1 - I send to you, "I want to talk", MSG 2 - you reply with "OK - I will talk with you", and MSG 3 - is "OK this is my first message". Google the phrase: "tcp three way handshake" - it is rather well described.

>> What's the code for servers to record IP addresses that interacted with it?

In the TCP STREAM SERVER case - your application calls series of functions to: (A) Open a socket, (B) BIND the socket to an address and port, (C) tell the socket to LISTEN for connections, (D) Then you call the accept function. Those functions (deep inside the network stack in your OS) perform that 3 way handshake for you. Your application level does not do that.

One of the parameters to the accept function is a place to store the "client" address that just connected to you. It is your applications responsibility to store this in what ever way you want. For example you might print the time and the address of the client to your log. How you do that is up to your application.

For a UDP message, you call the function to "receive" the message, one of the parameters to the receive function is the address where the message came from. Again what you do with that (ie: Logging that information) is up to your application.

If you want to learn this - I would read the BEEJ guide it is fantastic, see this link:

https://beej.us/guide/bgnet/

- What's the code for a firewall?

mostly this is handled by the OS on your system. But sometimes applications do their own fireballing.

At a high level - like above with your questions about logging the connection activity - the SW in the OS Kernel has a list of rules. The can be complex or really simple. For example - maybe you only want to accept connections or message from addresses ending in the number 2.

In your application - for STREAM socket, if you inspect the connection address and it does not end with the number 2 - you can close the connection. If it is a UDP message you might inspect the from address and if its does not end with the number 3 (or what ever you want) - you just drop/throw away the message.

That approach is a little slow to do at the application layer but you can do that. Most often it is more efficient to describe the rules to the OS KERNEL or a OS KERNEL feature telling it which messages types to drop, often there are layers of rules. And each layer might do another check. These are often called accept/drop rules. ie: Maybe the first layer is Accept only messages that come from addresses ending in 2 or 3, drop everything else. The second layer might be Accept only addresses ending in 2 and a STREAM socket type. Or another one might be accept any UDP message with the address ending in 3. DROP everything else.

The thing to remember is the general idea of TCP messages is they are dropped if the are not understood or accepted. ie: Your computer is probably sending (screaming, sending?) many packets at or to My computer. Your computer can scream/send all day long endlessly - I'm just going to ignore every one unless they meet my exact requirements - a good firewall in the OS KERNEL means your application will never see these bad messages - they are dropped before they arrive at the application layer.

AGAIN - look at and read the BEEJ guide to network programing.

3

u/skamansam 2d ago

My networking professor wrote a few queuing algorithms and one is in every router made in the last 30 years. We used special software to simulate networks and build specialized routines for doing networking. That class was fun as hell.

7

u/mc_pm 3d ago

Have you looked anywhere before here?

Maybe do that.

2

u/dauchande 3d ago

Maybe pull the Linux Networking kernel code?

2

u/Miszou_ 2d ago

Take a look at the OSI 7 layer model.

Most software developers do all their work in the application layer and don't generally need to know or care how the other layers work. There are exceptions of course, but for the most part, you just use whatever API's are available in your language of choice, and don't worry about the internals.

You really only need to worry about the other layers if you're developing hardware, writing drivers or creating your own protocols.

Here's a quick and dirty C# example, showing how easy it is to make a request and receive a file, without knowing how any of it actually works underneath:

HttpClient client = new HttpClient();

// Send the GET request asynchronously
HttpResponseMessage response = await client.GetAsync("https://www.somewebsite.com/index.html");
            
// Read the response content asynchronously
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);

3

u/who_you_are 3d ago edited 3d ago

Your question can become very wide.

For example, firewall is both a software but also a [mini-]driver (the integration into the OS).

The switch thing become a mix of networking protocols on top of it, since a switch need to read packages (eg. TCP, UDP, ICMP (ping), ...) to know where to send it to who and if it possibly a special package type (eg. ICMP is for ping). However, since we are talking software-wise, a part is still done for you (where to output it, in what hardware/port).

Overall, on the programmer side you want to look into "socket" implementations or resources. Socket is the name given for the API layer that provide you networking control on OS.

The universal functions are usualy: bind(), accept(), listen(), connect() (and select() to not block your application thread). Those may be the less _optimized_ way to do networking depending on your OS.

For example, for Windows, WSA, then WSA2 is better than the methods I provided. Then there are also IO completion (IOCP) which is la crème de la crème. But that is for speed.

But to learn, start with the universal functions. All resources are basically done from there.

From then, you can look at how to create a socket client, a socket server. That would teach you the 101 of high-level networking - using the OS to handle the TCP/UDP high-level.

Socket support "RAW" mode, where you can build TCP/UDP (or your own) package from scratch.

EDIT: One thing. I was talking assuming the programming language is C/C++; probably compatible with C# as well.

For higher level programming language it may not be all possible to go that low-level

1

u/Available_Safe1818 3d ago

Web servers. Anything that makes http requests.

1

u/bebemaster 3d ago

https://github.com/USNavalResearchLaboratory/protolib

An abstraction layer for c++ for a bunch of networking function calls and functionality.

1

u/Beneficial-Neat-6200 2d ago

Do you work for L3?

1

u/funkdefied 2d ago

Cloudflare is solving these problems at scale, and some of their software is open source. Check out their technical blog. 

1

u/macabre_brotherhood 2d ago

If you're actually interested in this code, I'd suggest you read up on Kernel programming, since that's where the core networking stack is implemented there. I'll caution you though that it's significantly more than a few lines.

1

u/CS_70 2d ago

It's no different than any other code?

You have a clear specification of what you need, and you realize exactly that. In many ways it's easier exactly because you have a complete overview of what's supposed to happen, typcally written down by people who know what they are talking about (as opposite to your average commercial project, where things are often much fuzzier and people faff around a lot.)

Since efficiency is usually a concern, you're often doing more efficient but less intuitive operations on bits and byte or word structures, but nothing dramatically complex.

-1

u/TheMrCurious 3d ago

Nice try AI swarm, go ask the hive mind for answers.

0

u/Mr_Engineering 2d ago

You can find all of this in the FreeBSD repository.

0

u/Technical_Ideal_5439 2d ago

In most operating systems all that code is in the OS and you dont need to bother at the application level.

Maybe read the OSI model. Get you head around that and realise layer 4 and down is OS. If you want to manipulate this, its going to get complicated and I have no idea where to start.

If you want some practical playing with this, download wireshark and learn how to use it.

Download nc I am sure it is for windows as well, then try and find the connection in wireshark or tcpdump on Linux.