rust


Convert String to SocketAddr


In versions of Rust before 1.0, I was able to use from_str() to convert a String to SocketAddr, but that function no longer exists. How can I do this in Rust 1.0.?
let server_details = reader.read_line().ok().expect("Something went wrong").as_slice().trim();
let server: SocketAddr = from_str(server_details);
let mut s = BufferedStream::new((TcpStream::connect(server).unwrap()));
from_str was renamed to parse and is now a method you can call on strings:
use std::net::SocketAddr;
fn main() {
let server_details = "127.0.0.1:80";
let server: SocketAddr = server_details.parse()
.expect("Unable to parse socket address");
println!("{:?}", server);
}
If you'd like to be able to resolve DNS entries to IPv{4,6} addresses, you may want to use ToSocketAddrs:
use std::net::{TcpStream,ToSocketAddrs};
fn main() {
let server_details = "stackoverflow.com:80";
let server: Vec<_> = server_details.to_socket_addrs()
.expect("Unable to resolve domain")
.collect();
println!("{:?}", server);
// Even easier, if you want to connect right away:
TcpStream::connect(server_details)
.expect("Unable to connect to server");
}
to_socket_addrs returns an iterator as a single DNS entry can expand to multiple IP addresses! Note that this code won't work in the Playground as network access is disabled there; you'll need to try it out locally.
I'll expand on "if you want to connect right away" comment in Shepmaster's answer.
Note that you don't really need to convert a string to a SocketAddr in advance in order to connect to something. TcpStream::connect() and other functions which take addresses are defined to accept an instance of ToSocketAddr trait:
fn connect<T: ToSocketAddr>(addr: T) -> TcpStream { ... }
It means that you can just pass a string to connect() without any conversions:
TcpStream::connect("stackoverflow.com:80")
Moreover, it is better not to convert the string to the SocketAddr in advance because domain names can resolve to multiple addresses, and TcpStream has special logic to handle this.

Related Links

Modeling embedded hardware in Rust and how to have multiple mutable references cleanly?
Should I borrow or copy my small data types?
Using pointer casting to change the “type” of data in memory [duplicate]
Export function only to module test?
Take slice of certain length known at compile time
Is it possible to deactivate file locking in cargo?
“does not live long enough” error in same function
What ways exist to create containers of several types? [duplicate]
How can I optimize reading a UTF-8 string from a file with a known offset and size?
Create vector of objects implementing a trait in Rust
Using loop variable from “..” loop causes type conversion?
What is RFC 401's coerce_inner useful for?
Rust Borrow checker only complains about borrowing as mutable multiple times when a function that returns a reference with the same lifetime assigned
How can I remove `let _ : () = …`?
Does if-let with a pair short-circuit?
Rust borrow lasts beyond the scope it's in?

Categories

HOME
flask
webview
paypal-ipn
enums
command-prompt
code-formatting
tabs
portable-class-library
liferay-7
google-sheets-query
fedora
stored-procedures
gprs
save
u-boot
yahoo
yeoman-generator-angular
heuristics
rangy
squirrel-sql
jodatime
bnf
uima
l20n
asciimath
scheduled-tasks
adminlte
weex
sharedpreferences
kaggle
batch-rename
vuforia
acrobat
bobo-browse.net
amazon-iam
commonsware-cwac
mongodb-3.4
android-canvas
pdfminer
ftp-server
elastica
sspi
slideshow
coverage.py
uiautomatorviewer
algebra
mongodb-aggregation
perl-data-structures
jsonix
data-management
clp
carmen
callouts
deferred-rendering
django-redis
polymerfire
teamviewer
taco
html.actionlink
opencyc
blockquote
supersocket.net
unidata
subfolder
python-c-extension
ssmtp
utf8-decode
qt5.4
mfmessagecomposeview
screwturn
code-complexity
usb-flash-drive
application-blocks
compiler-flags
progress-db
frontbase
san
jquery-transit
tfs-sdk
uitextfielddelegate
trialware
net-use
winsxs
uipasteboard
tablet-pc
asp.net-mvc-views
ccl
mongrel
chunking
outlook-2007-addin
tessellation
zend-test
ppc
firephp
projectpier
motif

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App