Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Created May 11, 2021 10:40
Show Gist options
  • Save HirbodBehnam/7cf0084cad1fe04ac26a5af3cccd44a1 to your computer and use it in GitHub Desktop.
Save HirbodBehnam/7cf0084cad1fe04ac26a5af3cccd44a1 to your computer and use it in GitHub Desktop.
A function to get your IP address from ipify.org. It doesn't use any libraries and writes raw input in connection.
use std::net::{TcpStream};
use std::io::{Write, BufReader, BufRead};
/// Connects to api.ipify.org and returns your IP address
/// Note that this method does not use any proxies
fn get_ip() -> Result<String, String> {
// at first, try to to connect to ipify
match TcpStream::connect("api.ipify.org:80") {
Ok(mut stream) => {
// create the request header; This is a const value
let msg = b"GET / HTTP/1.1\r\nHost: api.ipify.org\r\nConnection: close\r\n\r\n";
match stream.write(msg) { // write the header to stream
Ok(_) => {
let stream = BufReader::new(stream); // wrap stream to buf reader to read it line by line
let mut lines = stream.lines().map(|l| l.unwrap());
// read the first line of stream to make sure we got 200
match lines.next() {
Some(line) => {
if !line.ends_with("200 OK") {
return Err(String::from(format!("Server didn't return code 200! Code {} is returned.", line)));
}
}
None => {
return Err(String::from("Empty body from server"));
}
}
// read all next lines until we reach an "empty line". After that, the next line is the IP address
loop {
match lines.next() {
Some(line) => {
if line.len() == 0 { // check if the have reached the empty line
return Ok(lines.next().unwrap());
}
}
None => {
break;
}
}
}
}
Err(e) => { return Err(String::from(format!("Cannot write server's buffer: {}", e))); }
}
}
Err(e) => {
return Err(String::from(format!("Cannot connect to server: {}", e)));
}
};
return Err(String::from("Empty body from server"));
}
fn main() {
println!("{:?}", get_ip());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment