惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
B
Blog RSS Feed
V
V2EX
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
Scott Helme
Scott Helme
T
Threatpost
P
Privacy International News Feed
博客园 - Franky
Spread Privacy
Spread Privacy
K
Kaspersky official blog
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
L
Lohrmann on Cybersecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Exploit Database - CXSecurity.com
GbyAI
GbyAI
T
Tenable Blog
C
Cisco Blogs
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
I
Intezer
J
Java Code Geeks
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
Y
Y Combinator Blog
月光博客
月光博客
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
H
Help Net Security
D
Docker
M
MIT News - Artificial intelligence
AWS News Blog
AWS News Blog
Security Latest
Security Latest
C
CERT Recently Published Vulnerability Notes
Blog — PlanetScale
Blog — PlanetScale
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
T
Tor Project blog
The Cloudflare Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog

Arpit Bhayani

Temporal Primer - Building Long-Running Systems What Matters in Production RAG Structure of Every LLM Chat How LLMs Really Work Your Monolith Is Already A Distributed System Databases Were Not Designed For This BM25 JOIN Algorithms Venting at Work Comes at a Reputation Cost Why Half Your Skills Expire Every Few Years Multi-Paxos - Consensus in Distributed Databases MySQL Replication Internals Bloom Filters When You Increase Kafka Partitions Product Quantization The Q, K, V Matrices The Day I Accidentally Deleted Production How LLM Inference Works What are Blocking Queues and Why We Need Them Heartbeats in Distributed Systems How Writes Work in Apache Cassandra Redis Replication Internals How to Handle Arrogant Colleagues at Work How Does a CDN Handle Content Replication You Can't Fix Everything on Day One When Emotions Spill Over at Work Why gRPC Uses HTTP2 Meetings With No Agenda Are a Waste of Time Career Longevity Beats Constant Job Hopping Stay Relevant at Higher Salary Levels Why Distributed Systems Need Consensus Algorithms Like Raft Why Do Databases Deadlock and How Do They Resolve It Why and How Cache Locality Can Make Your Code Faster Why Eventual Consistency is Preferred in Distributed Systems Why does DNS use both UDP and TCP Should You Do a Master's My Honest Take Empathy Makes Great Engineers Unstoppable Good Mentors Build People, Not Just Skills Why You Should Always Have Back-Burner Projects Before You Push Back, Know What You're Standing On Be the One They Can Count On How Much Are People Willing to Bet on You How to Get Leadership to Say Yes to Your Project Don't Let Your Best Ideas Die in Silence Be the Person Everyone Wants to Work With The XY Problem and How to Avoid It The Startup Hiring Lie Nobody Talks About You Won't Be Promoted Unless You Ask It's Not Enough to be Right; Learn to be Heard No One Ships Great Software Alone You Don't Win by Proving Others Wrong Appreciate Generously; It Costs Nothing, But Builds Everything Your Soft Skills Aren't Soft at All Before you form an opinion, experience it Why You Need Both Curiosity and Action to Thrive A Daily Worklog Changed Everything How We Handle Mistakes Defines Us Own Your Mistakes Don't Wait. Step Up. Temporary Fixes Are Permanent Why Interviews Are Biased And What Sets You Apart Saying 'This isn't my problem' is actually the problem How to Write Effective OKRs Never Lose a Battle due to Miscommunication When In Doubt, Code It Out How to Follow Up Without Annoying People Lead Projects That Land, Execution Over Everything Abstract Thinking Will Define Your Next Decade We Engineers Suck at Task Estimation Shiny Obect Syndrome in Tech When to Change Jobs - The 3P Framework Comfort and Competition - Know When to Switch Gears Paper Notes - On-demand Container Loading in AWS Lambda Paper Notes - SQL Has Problems. We Can Fix Them Pipe Syntax In SQL Paper Notes - NanoLog - A Nanosecond Scale Logging System Don't Wait, Learn - The Best Resource is Mythical Paper Notes - WTF - The Who to Follow Service at Twitter The Unexpected Benefit of Reading Random Engineering Articles Roadmaps Are Limiting Your Growth Stop Leaving Money on the Table - Negotiate Your Job Offer Never Bad-Mouth Your Past Employers Show You're a Culture Fit Quantify your resume, Know Your Numbers The Importance of Being Likeable in Interviews Questions to Ask Your Interviewer How to Build Trust Through Collaboration Do This, Once You Are Out of the Interview Cycle Stop Pitching Ideas, Start Pitching Projects Read Those Design Docs, Even the Ones That Seem Irrelevant The Best Engineering Lessons Happen During Outages Great Engineers Start Broad LLM Summaries are Ruining Your Learning Turn System Design Interviews into Discussions Title Inflation At Work, Find Your Own Projects 6 Simple Strategies to Cracking Any Tech Interview How to Remain Unblocked Solving the Knapsack Problem with Evolutionary Algorithms Generating Pseudorandom Numbers with LFSR Local vs Global Indexes in Partitioned Databases
HTTP - The Hard Way with Netcat
Arpit Bhayani · 2016-04-12 · via Arpit Bhayani

Majority of the traffic over the internet is HTTP Traffic. There is a HTTP Client which wants some data from HTTP Server, so it creates a HTTP Request Message in the protocol understandable by the server and sends it. Server reads the message, understands it, acts accordingly and replies back with HTTP Response.

This complete process is abstracted by the tools like curl, requests libraries and utilities like Postman. Instead of using these tools and utilities, we shall go by the hard way and see HTTP messages in action.

The Webserver

For experimentation purpose let’s create a very basic webserver in Python Flask framework that exposes a trivial Hello World end point.

Python webserver script

from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello():
    return "Hello, World!"

app.run(port=3000)

Installing requirements

pip install flask

Start the webserver

python hello.py

The server listens on port 3000 . If you hit from the browser http://localhost:3000/hello, you should see Hello, World! rendered.

The HTTP Request Message

A HTTP Client talks to HTTP Server via a common protocol that is understandable by the two parties. A sample HTTP request message looks something like

GET /hello.html HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.sample-server.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

To understand more about HTTP Request messages, see references at the end of this article.

The HTTP Communication happens over a TCP Connection. So we create a TCP connection with the server and try to get response from it. To get a TCP connection I will use netcat.

Netcat

netcat is the utility that is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.

The webserver that was created above is listening on port 3000 . Lets create a TCP Connection and connect to it using netcat.

netcat localhost 3000

The command along with creating a TCP connection, will also open a STDIN. Anything passed in that input stream will reach the server via the connection. Lets see what happens when we provide This is a sample as input.

bad-request

The input message given is not a valid HTTP message hence server responded with a status code of 400 which is for Bad Request. And if you closely observe the server logs on flask application, you will see an entry of our last request.

Since the server is a HTTP Server, so it understands HTTP request. Let’s create one to hit our exposed API endpoint /hello .

The HTTP request message for this request looks something like this

GET /hello HTTP/1.1

And you should see output like this

get-request

The HTTP Server understands the message sent from the client and it responded back as directed by the source code.

Complex Requests and HTTP Request Messages

GET method with query params and headers

Following method exposes an endpoint which accepts a query parameter named name, and returns a response with name in it.

from flask import request

@app.route('/user')
def get_user():
    name = request.args.get('name')
    return "Requested for name = %s" % name

HTTP Request Message

Provide the HTTP request message below when STDIN opens up after you execute netcat command and connect with the server.

GET /user?name=arpit HTTP/1.1

Output

get-request-with-query-params

Basic POST Method example

Following method accepts form data via HTTP POST method and returns a dummy response with username and password in it.

from flask import request

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    return "Login successful for %s:%s" % (username, password)

HTTP Request Message

Provide the HTTP request message below when STDIN opens up after you execute netcat command and connect with the server.

POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

username=arpit&password=welcome

Output

post-request-with-form-data

POST Method with JSON Request Body

Following method accepts JSON data that contains a field id with integer value via HTTP POST method and returns a dummy response with id in it.

from flask import request

@app.route('/save', methods=['POST'])
def save_user():
    user_data = request.json
    return 'Saving user with id = %d' % (user_data.get('id'))

HTTP Request Message

Provide the HTTP request message below when STDIN opens up after you execute netcat command and connect with the server.

POST /save HTTP/1.1
Content-Type: application/json
Content-Length: 30

{"id": 1092, "name": "Arpit"}

Output

post-request-with-json-data

Conclusion

The hard way to hit REST endpoints was not hard at all ;-) Stay curious and dive deep.

References:

  1. HTTP/1.1: HTTP Message
  2. HTTP Requests - Tutorialspoint
  3. The TCP/IP Guide - HTTP Request Message Format
  4. HTTP Status Codes
  5. Netcat man page
  6. HTTP Methods